【问题标题】:When I use a method as a callback, it seems to lose access to `this`. Why?当我使用方法作为回调时,它似乎无法访问 `this`。为什么?
【发布时间】:2013-08-11 20:44:32
【问题描述】:

我在 Node 中使用express 来创建一个简单的网络应用程序。代码如下所示:

var get_stuff = function (callback) {
    another.getter(args, function (err, data) {
        if (err) throw err;

        data = do_stuff_to(data);

        callback(data);
    });
};

app.get('/endpoint', function (req, res) {
    get_stuff(res.send);
});

但是,当我运行它时,我得到了这个错误:TypeError: Cannot read property 'method' of undefined at res.send。正在破坏的快速代码是这样开始的:

res.send = function (body) {
    var req = this.req;
    var head = 'HEAD' == req.method;

在我看来,我构建回调的方式在send 方法中丢失了this。但我不知道如何解决它。有小费吗?谢谢!

【问题讨论】:

    标签: javascript methods callback this


    【解决方案1】:

    致电.bind:

    get_stuff(res.send.bind(res));
    

    并查看MDN documentation about this 以了解其工作原理。 this 的值由如何函数被调用决定。将其称为“正常”(回调可能会发生这种情况),例如

    func();
    

    this 设置为全局对象。仅当函数作为对象方法调用时(或.bind.apply.call 显式设置this),this 指的是对象:

    obj.fun(); // `this` refers to `obj` inside the function
    

    .bind 允许您在不调用函数的情况下指定this 值。它只是返回一个新函数,类似于

    function bind(func, this_obj) {
        return function() {
            func.apply(this_obj, arguments);
        };
    }
    

    【讨论】:

      【解决方案2】:

      在 JavaScript 中,this 的值是 generally determined by the call site,与 Python 不同,通过 . 运算符访问方法不会在稍后调用该方法时将其左侧绑定到 this

      要执行绑定,您可以像旧答案中一样调用.bind,或者您可以手动执行绑定,将方法调用包装在另一个回调中:

      get_stuff(function () {
          return res.send.apply(res, arguments);
      });
      

      从 ECMAScript 2018 开始,还可以使用粗箭头函数语法和剩余参数来使上述内容更加紧凑:

      get_stuff((...args) => res.send(...args));
      

      【讨论】:

        猜你喜欢
        • 2021-12-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-09-13
        • 2018-06-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多