在对象内创建指向函数的指针时 "这"未正确解决 试试这个例子来获得概念......
// this.* fail
a = { x : 123, f : function(){ console.log( this.x ) } }
a.f() // 123
b = a.f // b points to a.f now
b() // should print 123 but gaves 'undefined'
答案 0 :(得分:2)
来自https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this。
功能背景
在函数内部,其值取决于函数的方式 调用。
简单的通话
function f1(){ return this; } f1() === window; // global object
这是你在第二种情况b()
中所做的。您基本上是在全局对象上调用x。所以
var x = 456;
// this.* fail
a = { x : 123, f : function(){ console.log( this.x ) } }
a.f() // 123
b = a.f // b points to a.f now
b() // prints 456
作为对象方法
当一个函数作为一个对象的方法被调用时,它被设置为 调用该方法的对象。
在以下示例中,在函数内部调用o.f()时 这与o对象绑定。
var o = { prop: 37, f: function() { return this.prop; } }; console.log(o.f()); // logs 37
这是第一种情况。
答案 1 :(得分:2)
您可以使用bind
:
b = a.f.bind(a);
b(); // 123
来自MDN:
bind()方法创建一个新函数,在调用时, 将此关键字设置为提供的值,并使用给定的序列 调用新函数时提供的任何参数之前的参数。
答案 2 :(得分:1)
当您在实例上调用方法时,方法的上下文就是实例(this
方法中的f
关键字是a
在执行a.f()
时的引用}})。
但是,当您在变量中保留对函数的引用时,在调用它时,实际上会丢失上下文,因此this
成为全局上下文(在浏览器中为window
)。
因此,您需要在调用函数时为函数提供上下文,这要归功于call
或apply
方法:
您的代码变为:
b = a.f;
b.call(a); // or b.apply(a)
答案 3 :(得分:1)
您可以尝试将其分配给对象中的某个变量:
var a = {
x : 1,
self : this,
f : function() {
self.x++;
},
show : function() {
alert(self.x);
}
}
a.f();
a.show();
d = a.show;
d();