在Javascript中,為什么“this”操作符不一致?在JavaScript中,“this”操作符可以在不同的場景中引用不同的內(nèi)容。通常,在JavaScript“Object”中的方法中,它引用當前對象。但是,當用作回調(diào)時,它將成為對調(diào)用對象的引用。我發(fā)現(xiàn)這會導(dǎo)致代碼中的問題,因為如果使用JavaScript“Object”中的方法作為回調(diào)函數(shù),則無法判斷“this”指的是當前的“Object”還是“this”指的是調(diào)用的對象。有人能澄清如何解決這個問題的用法和最佳實踐嗎? 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');
}
}
在Javascript中,為什么“this”操作符不一致?
開滿天機
2019-08-03 07:03:48