我正在学习词汇 this
的传递,据我了解,粗箭头从其自身或其上方的函数获取“this”。如果这是一个常规函数,我的理解是它不会从高于此的函数中获取 this
。例如,这是我认为不应该运行的代码:
function test() {
this.a = 5; // test()' variable
this.b = function() {
//this is a fat arrow function so console log below could grab the this from this function's space, but not higher than this, but it does?
this.c = setTimeout(() => {
console.log(this.a);
}, 1000);
}
}
var d = new test();
d.b();
所以我希望 console.log 语句想要打印出 this.a
。它不存在于粗箭头函数上下文中,因此它会上升一级到匿名函数级别。这里也没有 this.a
。这是一个常规的非胖箭头函数,意味着根据我的理解,词法范围应该停在这里,它不应该上升到更高,但它确实上升了,我不确定为什么。为什么会发生这种情况?
最佳答案
因为您将函数 b 作为 d.b
调用,所以 this
是对象 d
。所以 this.a
相当于 d.a
。正如您已经观察到的,箭头函数将从其父作用域携带 this
,因此它能够将 this.a
解析为 d.a
。
function test() {
this.a = 5; // test()' variable
this.b = function() {
console.log("this.a in b: ", this.a);
this.c = setTimeout(() => {
console.log("this.a in c: ", this.a);
}, 1000);
}
}
var d = new test();
d.b();
如果将 d.b
放入单独的变量中,然后调用它,会发生什么?您会得到 undefined
- 因为 b
中的 this
现在引用全局范围。
function test() {
this.a = 5; // test()' variable
this.b = function() {
console.log("this.a in b: ", this.a);
console.log("this === window: ",this === window);
this.c = setTimeout(() => {
console.log("this.a in c:", this.a);
}, 1000);
}
}
var d = new test();
var myNewFunction = d.b;
myNewFunction();
关于javascript - 函数(带变量)->函数->粗箭头函数->这里显示的第一个函数的变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50539156/