[英]Constructor variables in prototype model not accessible after ajax call
從使用回調的異步調用返回時,無法訪問類的構造函數。
在這種情況下,我無法訪問Myclass1構造函數中定義的測試變量
我找不到解決方案,我在做什么錯?
var MyClass1 = function () {
this.test = 5;
};
MyClass1.prototype = function () {
//This is the function which calls another Myclass2 which contains the function for ajax //request
test = function () {
myClass2 = new MyClass2();
myClass2.getRequest.call(this, callback);
},
//This is the call Back
callback = function () {
alert(this.test); /*<---Cannot access this,shows undefined.In firebug it show this.test is not defined*/
};
return {
test: test,
callback: callback
}
}
MyClass2.prototype = function () {
getRequest = function () {
//make an async call set the success to the callback .I have propagated the data to //myclass1
$.ajax({
url: "test.html",
success: callBack.call(this, data) //<--I call the callback using myClass1
})
}
return {
getRequest: getRequest;
}
}
好的,所以有很多要點:
第一
在創建原型時,請聲明變量。 現在,您正在創建“ test”,“ callback”和“ getRequest”全局變量,因為您沒有使用“ var”
MyClass1.prototype = function () {
var test = function () {
// some code...
};
var callback = function () {
// some code...
};
// And more code...
};
“ test”聲明末尾的逗號是有效的,因為它是一個運算符,但是我很確定它不是您要執行的操作。
或者,您可以直接創建函數:
MyClass1.prototype = function () {
function test() {
// some code...
}
function callback() {
// some code...
}
// And more code...
};
第二
您正在為函數分配“原型”屬性
MyClass1.prototype = function() { ... };
這意味着您的類的原型是一個函數,具有方法“ call”,“ apply”,“ bind”但沒有“ test”或“ callback”。 可能您想創建立即調用的函數表達式(IIFE)
MyClass1.prototype = (function() {
function methodA() {
// some code...
}
return {
methodA: methodA
};
})();
或一個簡單的對象:
MyClass1.prototype = {
methodA: function() {
// some code...
},
methodB: function() {
// some code...
}
};
第三
我不明白您的代碼在做什么,“ MyClass2”在哪里定義,它擴展了“ MyClass1”?
第四
您正在將MyClass1原型上的“ test”屬性分配給一個函數,但是,在構造函數上,您將“ test”屬性分配給了一個數字,也許您想使用其他屬性。
第五
在這行上:
success: callBack.call(this, data)
您正在調用函數“回調”(我不知道它來自何處),重復一遍,您正在調用它,而不是將其設置為回調,您只是在調用函數並告訴$ .ajax比回調將是“ callback.call(this,data)”返回的值,可能是“ undefined”。
如果要將“回調”函數設置為ajax請求的回調,則需要傳遞一個函數,並且在該函數內部可以執行數組到達時要執行的任何操作,在這種情況下,請調用“回調”,但是必須保存為了使用它,使用“ this”變量:
var self = this;
$.ajax({
url: "test.html",
success: function(data) {
callBack.call(self, data);
}
})
我想數據變量來自ajax請求...
如您所見,在未測試代碼的情況下,很難給出准確的響應,因此,下次請提供您的代碼。
如果我所有的假設都正確:這是您需要的代碼: http : //jsfiddle.net/pw3hj/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.