JavaScript中的this

1.函数调用时的this


函数调用方法1:fn(p1,p2)
函数调用方法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新对象绑定


如果是一个构造函数,那么用new来调用,那么绑定的将是新创建的对象。
function Fn(){
this.a=1;
}
var fn=new Fn();
console.log(fn.a)//1 this => fn



3.bind() 对直接调用的影响


还有一点需要注意的是 bind() 的影响。Function.prototype.bind() 的作用是将当前函数与指定的对象绑定,并返回一个新函数,这个新函数无论以什么样的方式调用,其 this 始终指向绑定的对象。还是来看例子:
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 不会像预期那样执行,比如


const obj = {};
 
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


由此可见,bind() 对函数的影响是深远的,慎用!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值