分配给其他变量时Javascript丢失了上下文 [英] Javascript lost context when assigned to other variable

查看:68
本文介绍了分配给其他变量时Javascript丢失了上下文的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么在javascript中,如果您将object方法引用到某个变量,则会丢失该对象的上下文.找不到任何与解释相关的链接.除了以下说明: 此"是指拥有"方法的对象,其中不可能是真的.

Why in javascript if you reference objects method to some variable it loses that objects context. Can't find any link with explanation what happens under the hood. Except this one which states: ‘this’ refers to the object which ‘owns’ the method which doesn't seam to be true.

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)时,我们将其称为方法,并且隐式为其父对象的上下文分配了

It depends on how a function is called. If a function is not referenced through being an attribute of an object (e.g. refToMethod) then it will be assigned the "Global context" which is window. However, when a function is an attribute of object (e.g. obj.method), we refer to it as a method, and it is implicitly assigned the context of it's parent object.

JavaScript的上下文不同于许多语言,因为您可以使用 .apply() .此外,ECMAScript 5引入了新的 .bind() 方法,使您可以创建始终绑定到同一上下文的方法的副本. 有关详细信息,请参见MDN .

JavaScript's context is unlike many languages in that you can override it easily using either .call() or .apply(). Furthermore, ECMAScript 5 introduced a new .bind() method to allow you to create copies of methods which are always bound to the same context. 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丢失了上下文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆