[英]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.