2016-12-29 136 views
0

我希望位于我的ajax调用中的函数能够访问调用范围内的变量“this”。我想避免尽可能多的硬编码,因此我不得不寻求帮助。这里有一些想法。将对象传递给函数调用中的函数

  • 在ajax函数中添加一个可选参数,该参数将作为回调调用中的参数发送。它不会很漂亮,但它肯定会奏效。
  • 发送带有ajax的对象引用,用php接收并发送回去,然后通过响应来访问它。这可以省去ajax的功能,但将混乱传递给后端。

// Working ajax function | The problem is below this 
 
function ajax(protocol = "GET", url = "", callback = function(response){ console.log(response); }, data = null){ 
 
\t 
 
\t // Build data 
 
\t var formData = null; 
 
\t if(data !== null){ 
 
\t \t formData = new FormData(); 
 
\t \t for(var instance in data){ 
 
\t \t \t formData.append(instance, data[instance]); 
 
\t \t } 
 
\t } 
 

 
\t // Build essential ajax components 
 
\t var xhr = new XMLHttpRequest(); 
 
\t xhr.open(protocol, url, true); 
 
\t 
 
\t // Check for state updates 
 
\t xhr.onreadystatechange = function(){ 
 
\t \t if(xhr.readyState === XMLHttpRequest.DONE){ 
 
\t \t \t if(xhr.status === 200){ 
 
\t \t \t \t callback(xhr.responseText); 
 
\t \t \t } 
 
\t \t \t else{ 
 
\t \t \t \t callback("Error code: " + xhr.status); 
 
\t \t \t } 
 
     } 
 
\t } 
 

 
\t // Send it! 
 
\t 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>

+0

[JavaScript的如何获得在回调函数this.variable](可能的重复http://stackoverflow.com/questions/14670359/javascript如何获得这个变量在回调函数) – skyline3000

回答

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

0123你这是指窗口

var context = this; 

的回调中,使用情境... ,就像它的名字由窗口对象功能(你的Ajax功能):

1

可以存储这一点。 顺便说一句,你的代码是错误的(原型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"}); } 
+0

谢谢!我简化了我的代码而不进行测试,这就是为什么该方法不正确。 –