gpt4 book ai didi

Javascript 在分配给其他变量时丢失了上下文

转载 作者:搜寻专家 更新时间:2023-11-01 04:17:07 25 4
gpt4 key购买 nike

为什么在 javascript 中,如果您将对象方法引用到某个变量,它会丢失该对象上下文。找不到任何链接来解释引擎盖下发生的事情。除了这个声明: ‘this’ refers to the object which ‘owns’ the method这似乎不是真的。

var Class = function() {
this.property = 1
}

Class.prototype.method = function() {
return this.property;
}

var obj = new Class();
console.log(obj.method() === 1);

var refToMethod = obj.method; // why refToMethod 'this' is window


console.log(refToMethod() !== 1) // why this is true?

var property = 1;
console.log(refToMethod() === 1)

最佳答案

这取决于函数的调用方式。如果函数不是通过对象的属性(例如 refToMethod)来引用的,那么它将被分配到“全局上下文”,即 window。但是,当函数是对象的属性时(例如 obj.method),我们将其称为方法,并隐式为其父对象分配上下文。

JavaScript 的上下文不同于许多语言,因为您可以使用 .call() 轻松覆盖它。或 .apply() .此外,ECMAScript 5 引入了一个新的 .bind()方法允许您创建始终绑定(bind)到相同上下文的方法的副本。 See MDN for more .

var obj = new Class();
obj.method(); // 1;

var unbound = obj.method;
unbound(); // undefined;

// Call and Apply setting the context to obj.
unbound.apply(obj); // 1
unbound.call(obj); // 1;

// ECMAScript 5's bind
var bound = unbound.bind(obj);
bound(); // 1;

关于Javascript 在分配给其他变量时丢失了上下文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23154778/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com