我基本上有一个对象,通过其原型扩展了一个函数。在该函数内部,存在另一个函数,但是当在此嵌套函数中使用this
时,它似乎不是指向对象,而是指向函数。
例如,
var sampleObject = function() {
this.foo = 123;
}
sampleObject.prototype.getFoo = function() {
var nested = function() {
return this.foo;
}
return nested();
}
var test = new sampleObject();
window.alert(test.getFoo()); // undefined
this.foo
并不指向123值,而是未定义的,因为它指向嵌套函数,在其中没有foo
存在。如何从嵌套函数中访问123值?
var foo = new sampleObject();
$(window).on('scroll', foo.getFoo );
- vsyncthis
,所以在你的例子中var me = this;
将指向window
对象。 - vsync.bind()
或其他方法来为您完成它。 - Pointy