我正在尝试使用“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”绑定(bind)到 async.series 函数,或者我应该只将我的值作为参数传递?
最佳答案
正如@Pointy 所指出的,.bind() 实际上是正确的方法。 经过一些研究,我是如何解决我的问题的。
search.prototype.test = function() {
async.series({
songId: this.getSongId.bind(this) //binding "this" here!
}, function(err, results) {});
};
谢谢:)
关于javascript - 从 async.series 调用的原型(prototype)函数中使用 'this',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27549357/