gpt4 book ai didi

javascript - 将对象传递给函数调用内的函数

转载 作者:行者123 更新时间:2023-12-02 13:46:13 24 4
gpt4 key购买 nike

我希望位于我的 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){

// 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>

最佳答案

您的问题有多种解决方案

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"});
}

关于javascript - 将对象传递给函数调用内的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41382916/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com