Javascript & # 39;未定义# 39;变量.映射到原型函数上

Javascript 'undefined' variable when using async.map on prototype functions

本文关键字:原型 函数 未定义 Javascript 变量 映射      更新时间:2023-09-26

我想使用奇妙的异步模块为NodeJS编写一些不错的Javascript代码。我有一个值数组,我想对每个值调用一个特定的函数,并在数组中积累结果:我使用async。这是地图。不幸的是,如果我尝试调用的函数是我的类的原型函数,它将无法读取变量值。

这是我定义的一个测试"类"。

var async = require('async');
function ClassA() {
    this.someVar = 367;
};
ClassA.prototype.test1 = function(param, callback) {
    console.log('[' + param + ']The value in test is: ' + this.someVar);
    callback(null, param + this.someVar);
};
ClassA.prototype.test2 = function() {
    var self = this;
    async.map([1,3,4,5], (self.test1), function(err, result){
        if (err) {
            console.log('there was an error')
        } else {
            console.log('Result is: ' + result)
        }
    })
};
module.exports = new ClassA();

我是这样使用的

testclass.test1(1, function(err, data){});
testclass.test2();

输出:

[1]The value in test is: 367
[1]The value in test is: undefined
[3]The value in test is: undefined
[4]The value in test is: undefined
[5]The value in test is: undefined
Result is: NaN,NaN,NaN,NaN

可以看到,通过使用async.maptest2获得的输出不能访问this.someVar变量。

我肯定遗漏了什么。谁能指出我的错误,并解释为什么它不能工作?我希望367出现在那些未定义的地方。我认为这个问题与这个SO问题有关,但我似乎找不到解决我的用例的方法。

感谢您的阅读,很抱歉问题太长了!

我不是那个库的专家(事实上,我从未使用过它)。

但是看看它的文档中的这一节,我认为问题在于你传递给迭代器的是函数本身,但是在它自己的上下文中异步调用该函数,这意味着函数内的this参数不是你所期望的。

尝试遵循文档的建议(使用bind)来避免这个陷阱。