var x = 3;
var one = {
x:2,
two: {
x:1,
three:function(){
return this.x;
}
}
}
var go = one.two.three;
console.log(one.two.three() + "" + go());
任何人都可以向我解释为什么输出是 13 为什么不是 1-undefined?
最佳答案
this
关键字具有不同的绑定(bind),可以在运行时更改,具体取决于调用函数的方式。
当函数位于对象上并通过该对象访问时,它的 this
上下文将是该对象(除非另外明确绑定(bind),但稍后我会添加注释)。这意味着 this.x
引用与 one.two.x
当您将同一个函数引用到一个全局变量中时,this
上下文就变成了全局空间(例如浏览器上的 window
对象,或者 globalThis
在 NodeJS 中)。发生这种情况时,this.x
现在正在引用全局变量 x
。
还有其他一些this
上下文规则不同的情况,例如函数闭包或类函数。
函数也有 .bind
方法,它返回一个带有显式绑定(bind)的 this
变量的新函数。
例如:
var x = 3;
var one = {
x:2,
two: {
x:1,
three:function(){
return this.x;
}
}
}
one.two.three = one.two.three.bind(one);
var go = one.two.three;
console.log(one.two.three() + "" + go()); // prints 22
还有箭头函数,它隐式地将 this
上下文绑定(bind)到它的词法范围...例如:
var x = 3;
var one = {
x:2,
two: {
x:1,
three: () => {
return this.x;
}
}
}
var go = one.two.three;
console.log(one.two.three() + "" + go()); // prints 33
上面的例子打印 33,因为词法作用域是全局作用域,因此 this.x
引用了全局变量 x
。
希望这能在不产生更多问题的情况下回答您的问题。
进一步阅读:
关于JavaScript 对象相关的问题,下面代码的输出是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71045035/