在原型函数上使用async.map时,Javascript'undefined'variables

我想用奇妙的asynchronous模块为NodeJS编写一些不错的Javascript代码。 我有一个值的数组,我想调用每个值的特定函数,并积累在一个数组的结果:我使用async.map这个。 不幸的是,如果我尝试调用的函数是我的类的原型函数,则无法读取variables值。

示例这是我定义的一个testing“类”。

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 

正如你所看到的,通过test2获得的输出使得async.map无法访问this.someVarvariables。

问题我肯定在这里错过了一些东西。 有人可以指出我的错误,并解释为什么它不工作? 我期望367出现在那些未定义的地方。 我认为这个问题与这个问题有关 ,但我似乎无法find解决scheme。

感谢您的阅读和抱歉的问题的长度!

我不是那个图书馆的专家(实际上我从来没有用过)。

但是在文档中查看这一节 ,我认为问题在于你传递给迭代器的是函数本身,而asynchronous调用函数在它自己的上下文中,这意味着函数中的this参数isn你所期待的那个。

尝试遵循文档build议(使用绑定)来避免这个陷阱。