当我使用一个方法作为回调时,它似乎无法访问“this”.为什么?

When I use a method as a callback, it seems to lose access to `this`. Why?

本文关键字:访问 为什么 this 回调 方法 一个      更新时间:2023-09-26

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

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。但我不知道该怎么修。有什么建议吗?谢谢

调用.bind:

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

并查看有关this的MDN文档以了解其工作原理。this的值由函数的调用方式决定。称其为"正常"(回调可能会发生什么),如

func();

将CCD_ 8设置为全局对象。仅当函数被调用为对象方法时(或者如果this被明确设置为使用.bind.apply.call),this指对象:

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

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

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

在JavaScript中,this的值通常由调用站点决定,与Python不同,当稍后调用方法时,通过.运算符访问方法不会将其左侧绑定到this

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

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

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

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