1.函数调用时的this
函数调用方法2:obj.child.method(p1,p2)
函数调用方法3:fn.call(undefined,p1,p2)
this 指的就是函数调用的第三种方法call中第一个参数,当第一个参数为undefined时 this指向window
fn(p1,p2) => fn.call(undefined,p1,p2) this=> window
obj.child.method(p1,p2) => obj.child.method.call(obj.child,p1,p2) this =>obj.child
2.new新对象绑定
function Fn(){
this.a=1;
}
var fn=new Fn();
console.log(fn.a)//1 this => fn
3.bind() 对直接调用的影响
const obj = {};
function test() {
console.log(this === obj);
}
const testObj = test.bind(obj);
test(); // false
testObj(); // true
那么 bind() 干了啥?不妨模拟一个 bind() 来了解它是如何做到对 this 产生影响的。
const obj = {};
function test() {
console.log(this === obj);
}
// 自定义的函数,模拟 bind() 对 this 的影响
function myBind(func, target) {
return function() {
return func.apply(target, arguments);
};
}
const testObj = myBind(test, obj);
test(); // false
testObj(); // true
从上面的示例可以看到,首先,通过闭包,保持了 target,即绑定的对象;然后在调用函数的时候,对原函数使用了 apply 方法来指定函数的 this。当然原生的 bind() 实现可能会不同,而且更高效。但这个示例说明了 bind() 的可行性。
4.call 和 apply 对 this 的影响
上面的示例中用到了 Function.prototype.apply(),与之类似的还有 Function.prototype.call()。这两方法的用法请大家自己通过链接去看文档。不过,它们的第一个参数都是指定函数运行时其中的 this 指向。
不过使用 apply 和 call 的时候仍然需要注意,如果目录函数本身是一个绑定了 this 对象的函数,那 apply 和 call 不会像预期那样执行,比如
function test() {
console.log(this === obj);
}
// 绑定到一个新对象,而不是 obj
const testObj = test.bind({});
test.apply(obj); // true
// 期望 this 是 obj,即输出 true
// 但是因为 testObj 绑定了不是 obj 的对象,所以会输出 false
testObj.apply(obj); // false