我希望我的ajax调用中的函数可以访问变量"这个"在它被调用的范围内。我想避免尽可能多的硬编码,因此我不得不寻求帮助。这里有一些想法。
// Working ajax function | The problem is below this
function ajax(protocol = "GET", url = "", callback = function(response){ console.log(response); }, data = null){
// Build data
var formData = null;
if(data !== null){
formData = new FormData();
for(var instance in data){
formData.append(instance, data[instance]);
}
}
// Build essential ajax components
var xhr = new XMLHttpRequest();
xhr.open(protocol, url, true);
// Check for state updates
xhr.onreadystatechange = function(){
if(xhr.readyState === XMLHttpRequest.DONE){
if(xhr.status === 200){
callback(xhr.responseText);
}
else{
callback("Error code: " + xhr.status);
}
}
}
// Send it!
xhr.send(formData);
}
// My class
function MyClass(el){
this.target = el;
this.fetch(); // Call the fetch method
}
MyClass.prototype.fetch(){
this; // "This" works perfectly in this scope as it refers to myInstance in this example
ajax("POST", "target/path.php", function(response){
var newEl = document.createElement("div");
newEl.innerHTML = response;
// HERE's THE RPOBLEM
this.target.appendChild(newEl); // "this" refers to the window object..
}, {data: "data"});
}
var myTarget = document.getElementById("myTarget");
var myInstance = new MyClass(myTarget);

<div id="myTarget"></div>
&#13;
答案 0 :(得分:1)
您的问题有多种解决方案
1)你可以创建一个闭包
MyClass.prototype.fetch(){
this; // "This" works perfectly in this scope as it refers to myInstance in this example
var that = this;
ajax("POST", "target/path.php", function(response){
var newEl = document.createElement("div");
newEl.innerHTML = response;
// HERE's THE RPOBLEM
that.target.appendChild(newEl); // "this" refers to the window object..
}, {data: "data"});
}
2)您可以使用bind method
MyClass.prototype.fetch(){
this; // "This" works perfectly in this scope as it refers to myInstance in this example
ajax("POST", "target/path.php",(function(response){
var newEl = document.createElement("div");
newEl.innerHTML = response;
// HERE's THE RPOBLEM
this.target.appendChild(newEl); // "this" refers to the window object..
}).bind(this), {data: "data"});
}
答案 1 :(得分:1)
可以存储:
var context = this;
在回调中,使用上下文... 你的这是指窗口,因为它是由窗口对象函数(你的ajax函数)调用的。 顺便说一句,你的代码是错误的(原型dec):
MyClass.prototype.fetch=function(){
var context=this; // "This" works perfectly in this scope as it refers to myInstance in this example
ajax("POST", "target/path.php", function(response){
var newEl = document.createElement("div");
newEl.innerHTML = response;
// HERE's NOT THE RPOBLEM
context.target.appendChild(newEl); // "context" refers to the MyClass Object object..
}, {data: "data"}); }