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库,没有参数。我想我可以修改一下,这就是你的建议吗?