javascript - 从 async.series 调用的原型(prototype)函数中使用 'this'

标签 javascript node.js asynchronous this

我正在尝试使用“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/

相关文章:

Javascript 将表单中的名字大写

python - 异步处理数组中的多个文件 - Python

javascript - 在 Node 的 Promise 中调用类的其他函数

javascript - NodeJS : Async comportment not wanted

asp.net-mvc-3 - 用于从 Entity Framework 异步加载的 MVC3 异步 Controller

javascript - 如何防止 Unicode 字符从 JavaScript 呈现为 HTML 中的表情符号?

java - 将 Java 对象从 JavaScript 发送到 Applet

javascript - 我如何在 React Native 中从 json 中选择一个特定的值?

javascript - 如何使用 QuillJs 和 body-parser 提交表单?

javascript - 为什么对引用的引用不会更新原始对象?