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