this的牛逼使用

let a =  1 ;
 
class   Foo {
   a =  2
   test = () => {
     console.log( this .a);
   }
}
 
let bar = {
   a:  3 ,
   test: () => {
     console.log( this .a);
   },
   test2: function() {
     console.log( this .a);
   }
}
 
 
// 给出以下6个结果
Foo.test();
bar.test();
bar.test2();
bar.test.bind(Foo)();
bar.test2.bind(Foo)();
bar.test2.bind(Foo).bind(bar)();
 
// 附加题:给出以下3个结果
let foo =  new   Foo();
foo.test();
bar.test2.bind(foo)();
bar.test2.bind(foo).bind(bar)();


标准答案:

第一批题:

报错(没有实例化,也不是静态方法,取不到test方法)
非严格模式:undefined、严格模式:报错(非严格模式let a = 1并没有把 a 绑定到 window/global 上,其实是window.a/global.a,是 undefined ,严格模式  其实是undefined.a)
3
非严格模式:undefined、严格模式:报错 (箭头函数的this 指向无法被 bind 修改,答案同第二题,不受bind影响)
undefined (Foo根本没有实例化)
undefined (this指向只能改变一次,答案同上一题)

第二批题:

2(已经实例化)
2
2(this 指向只能改变一次)

 

 

解析以 MDN 的文档为准:https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Operators/this

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值