var foo = {
_name: 'John',
getIdentity: function (){
return this._name;
}
};
var stoleIdentity = foo.getIdentity;
console.log(stoleIdentity());
console.log(foo.getIdentity());
嗨,我可以知道吗,是否还有其他实现方法可以实现与上述代码相同的结果?
为什么我无法获得stoleIdentity
的结果?
答案 0 :(得分:3)
this
由非常具体的情况定义;我们感兴趣的是一个“方法调用”,看起来像这样:
receiver.method(argument_list...)
如果在函数调用中没有提到接收器,则它是普通函数调用,而不是方法调用,并且this
未设置。
因此,foo.getIdentity()
是一种方法调用,将this
设置为foo
,this._name
评估为foo._name
; stoleIdentity()
是普通的函数调用,不会更改this
,this._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());