Javascript:引用变量

时间:2018-02-21 05:07:09

标签: javascript

    var foo = {
    _name: 'John',
    getIdentity: function (){
        return this._name;
    }
};

var stoleIdentity = foo.getIdentity;

console.log(stoleIdentity());
console.log(foo.getIdentity());

嗨,我可以知道吗,是否还有其他实现方法可以实现与上述代码相同的结果?

为什么我无法获得stoleIdentity的结果?

2 个答案:

答案 0 :(得分:3)

JavaScript中的

this由非常具体的情况定义;我们感兴趣的是一个“方法调用”,看起来像这样:

receiver.method(argument_list...)

如果在函数调用中没有提到接收器,则它是普通函数调用,而不是方法调用,并且this未设置。

因此,foo.getIdentity()是一种方法调用,将this设置为foothis._name评估为foo._name; stoleIdentity()是普通的函数调用,不会更改thisthis._name可能会访问window._name,除非this在此期间以其他方式更改

您可以使用Function.prototype.bind将接收器绑定到函数值(其他一种更改this的方法)。因此,如果您使用此行,您的代码将起作用:

var stoleIdentity = foo.getIdentity.bind(foo);

答案 1 :(得分:0)

当你将foo.getIdentity分配给stoleIdentity时,这个被改变了。您可以将其记录下来进行检查。

使用此绑定将其绑定到stoleIdentity以使其正常工作。



var foo = {
    _name: 'John',
    getIdentity: function (){
        return this._name;
    }
};

var stoleIdentity = foo.getIdentity.bind(foo);

console.log(stoleIdentity());
console.log(foo.getIdentity());