使用从 async.series 调用的原型函数中的“this”

Using 'this' from a prototype function called from async.series

本文关键字:函数 this 原型 async series 调用      更新时间:2023-09-26

我试图使用"this"访问变量,但上下文发生了变化,因为我的函数被async.series调用了。这是我的代码示例:)

var search = function(url) {
    this.music = url;
}
search.prototype.test = function() {
    async.series({
        songId: this.getSongId
    }, function(err, results) {});
};
search.prototype.getSongId = function(callback) {
    console.log(this.music) // Prints 'undefined'
}
module.exports = search;

当我在做

var engine = require('./lib/index.js');
var search = new engine('test');
search.test();

我得到"未定义"。有没有办法将"this"绑定到 async.series 函数,或者我应该只将我的值作为参数传递?

正如@Pointy所指出的,.bind(( 实际上是正确的方法。经过一些研究,这就是我如何解决我的问题。

search.prototype.test = function() {
    async.series({
        songId: this.getSongId.bind(this) //binding "this" here!
    }, function(err, results) {});
};

谢谢:)