2012-10-09 32 views
0

是否可以引用外部函數的上下文,而不用將上下文重新分配給某個局部變量?引用外部上下文而不重新分配

例如:

var objects = []; 

// populate objects 

Foo.prototype.bar = function() { 
    var outerObject = this; 
    $.each(objects, function() { 
     this.someMethod(outerObject); 
    }); 
}; 

回答

1

你可以使用.bind,否則,您必須存儲this與局部變量。

Foo.prototype.bar = function() { 
    var outerObject = this; 
    var inner = (function() { 
     // do something with outerObject 
     console.log(this === outerObject); 
    }).bind(this); 
}; 

更新:

對於您的情況:

var objects = []; 

// populate objects 

Foo.prototype.bar = function() { 
    $.each(objects, (function (obj) { 
     this.someMethod(obj); 
    }).bind(this)); 
}; 
+0

哦,太棒了!我不知道那件事。 – TheOne

+0

我不認爲這將與jQuery事件處理程序一起工作。 – TheOne

+0

@Ramin爲什麼不呢?沒有任何與jQuery衝突。 – xdazz

相關問題