在Javascript中,为什么“this”操作符不一致?在JavaScript中,“this”操作符可以在不同的场景中引用不同的内容。通常,在JavaScript“Object”中的方法中,它引用当前对象。但是,当用作回调时,它将成为对调用对象的引用。我发现这会导致代码中的问题,因为如果使用JavaScript“Object”中的方法作为回调函数,则无法判断“this”指的是当前的“Object”还是“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');
}
}
3 回答
米琪卡哇伊
TA贡献1998条经验 获得超6个赞
this
this
myObject.myFunction();
this
myFunction
myObject
function TestObject() { TestObject.prototype.firstMethod = function(){ this.callback(); YAHOO.util.Connect.asyncRequest(method, uri, callBack); } var that = this; TestObject.prototype.callBack = function(o){ that.secondMethod(); } TestObject.prototype.secondMethod = function() { alert('test'); }}
添加回答
举报
0/150
提交
取消