我在我的javascript代碼中有this
範圍的兩個大問題。 創建setAJAXGet
對象後,回調函數丟失,無法正確調用。所以,而不是打電話this.funct
我設置ajax.parent = this
;並致電this.parent.funct
- 工作正常。xmlhttprequest中的「this」範圍的雙重問題javascript
function setAJAXGet() {
this.askServer = function() {
var ajax = new XMLHttpRequest();
ajax.parent = this;
ajax.contentType = "charset:utf-8";
ajax.onreadystatechange = function() {
if (ajax.readyState==4 && ajax.status==200) {
this.parent.funct(ajax.responseText);
}
}
ajax.open("GET", this.url+'?'+this.vars, true);
ajax.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
if (navigator.onLine) ajax.send(null); else this.functError();
}
this.functError;
this.funct;
this.vars;
this.url;
}
事情變得更加複雜,當我嘗試調用從另一個對象setAJAXGet()
和回調函數是對象內。回調函數被正確調用,但對象中的其他函數(來自回調函數)不可見。
function someObject() {
this.asyncGet = function() {
var get = new setAJAXGet();
//do some config here...
get.funct = this.processAsyncData;
get.askServer();
}
this.someOtherFunction = function() {
}
this.processAsyncData = function(ajaxText) {
// ajaxText is OK
this.someOtherFunction();
// this.someOtherFunction is not defined (how so?)
}
this.asyncGet();
}
我可以通過修改setAJAXGet()
傳遞對象給processAsyncData
作爲參數解決這個問題,但它看起來醜陋。
function someObject() {
this.asyncGet = function() {
var get = new modifiedSetAJAXGet();
//do config here...
get.object = this; // stores 'this' and sends it to callback as argument
get.funct = this.processAsyncData;
get.askServer();
}
this.someOtherFunction = function() {
}
this.processAsyncData = function(object, ajaxText) {
// ajaxText is OK
object.someOtherFunction();
// object.someOtherFunction works just fine
}
this.asyncGet();
}
我相信你知道更優雅的解決方案。
我建議你閱讀這篇關於'this'值如何設置的入門書:http://stackoverflow.com/questions/28016664/when-you-pass-this-as-an-argument/28016676# 28016676 – jfriend00
爲什麼不把經典的'var self = this'放在函數的頂部? – Mathletics
@Mathletics我應該在哪裏放'var self = this'? –