【发布时间】:2010-09-09 22:53:56
【问题描述】:
在 JavaScript 中,“this”操作符在不同的场景下可以指代不同的事物。
通常在 JavaScript“对象”中的方法中,它指的是当前对象。
但是当用作回调时,它变成了对调用对象的引用。
我发现这会导致代码出现问题,因为如果您使用 JavaScript“对象”中的方法作为回调函数,您将无法判断“this”是指当前“对象”还是“this”指调用对象。
有人可以澄清有关如何解决此问题的用法和最佳实践吗?
function TestObject() {
TestObject.prototype.firstMethod = function(){
this.callback();
YAHOO.util.Connect.asyncRequest(method, uri, callBack);
}
TestObject.prototype.callBack = function(o){
// do something with "this"
//when method is called directly, "this" resolves to the current object
//when invoked by the asyncRequest callback, "this" is not the current object
//what design patterns can make this consistent?
this.secondMethod();
}
TestObject.prototype.secondMethod = function() {
alert('test');
}
}
【问题讨论】:
-
基于上下文here的神秘这种行为的一个很好的解释
标签: javascript