Javascript 维护原始回拨”功能;这";具有绑定功能
我知道Javascript 维护原始回拨”功能;这";具有绑定功能,javascript,callback,Javascript,Callback,我知道bind创建了一个新函数,并替换了这个值。榜样 function edit(req, res) { db.User.findById('ABCD', (function(err, user){ this.foo(user); }).bind(this)); }; 从 具有提供自己参数的回调函数 我正在使用http.min.js,它处理如下回调: http.get({ url: "http://localhost:8080/player/stat
bind
创建了一个新函数,并替换了这个值。榜样
function edit(req, res) {
db.User.findById('ABCD', (function(err, user){
this.foo(user);
}).bind(this));
};
从
具有提供自己参数的回调函数
我正在使用http.min.js
,它处理如下回调:
http.get({
url: "http://localhost:8080/player/status/" + name,
onload: function() {
console.log(this.responseText);
请注意,缺少传入的字符串-this.responseText
将为我提供一个可以解析为JSON
的字符串
从http.min.js
回调中维护“this”并绑定到我的回调函数的最简单方法是什么
我喜欢
http.get({
url: "http://localhost:8080/player/status/" + name,
onload: this.handlePlayerInfo.bind(this);
如果可能的话,我想使用它,而不是使用var-that
使用库:使用var似乎是保持回调“this”状态的唯一方法
我会的
Callback.hell = this;
http.get({
url: "http://localhost:8080/join/" + Player.name,
onload: this.handleJoin;
});
handleJoin(res) {
var json = JSON.parse(JSON.parse(this.responseText));
console.log("join" + j);
console.log(j.name);
Callback.hell.status.auth = j.auth;
Callback.hell.status.name = j.name;
Callback.hell.getPlayerInfo();
}
看起来使用var是保持回调“this”状态的唯一方法
我会的
Callback.hell = this;
http.get({
url: "http://localhost:8080/join/" + Player.name,
onload: this.handleJoin;
});
handleJoin(res) {
var json = JSON.parse(JSON.parse(this.responseText));
console.log("join" + j);
console.log(j.name);
Callback.hell.status.auth = j.auth;
Callback.hell.status.name = j.name;
Callback.hell.getPlayerInfo();
}
那么,当您以.bind()
所示的方式尝试时,会发生什么情况呢?我肯定这不起作用,那么您就无法访问http
的this
。如果您使用bind,您将无法从http访问this
。如果不使用bind,则必须在handlePlayerInfo
中使用var
。您不使用.then()
而不是onload
有什么原因吗?这样,您可以将this
设置为任何您喜欢的值,并将响应作为参数接收。。。(或者onload
处理程序是否收到任何参数?)nnnnn onload来自http.min.js库,没有参数。我可以修改它,我想,这就是你的建议吗?那么,当你用.bind()
所示的方式尝试它时发生了什么?我确信这不起作用,那么你就不能访问http
的this
。如果你使用bind,你就不能从http访问this
。如果不使用bind,则必须在handlePlayerInfo
中使用var
。您不使用.then()
而不是onload
有什么原因吗?这样,您可以将this
设置为任何您喜欢的值,并将响应作为参数接收。。。(或者onload
处理程序是否收到任何参数?)nnnnn onload来自http.min.js库,没有参数。我想我可以修改一下,这就是你的建议吗?