使用从 async.series 调用的原型函数中的“this”
Using 'this' from a prototype function called from async.series
我试图使用"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) {});
};
谢谢:)
相关文章:
- 在另一个函数中使用变量this
- JavaScript 中的嵌套函数和 “this” 关键字
- javascript中对象构造函数中的var属性与this.properties
- 函数中this和var之间的区别
- 在JavaScript类型的函数中避免self-this
- 如何使用(this)访问Angular 2 http rxjs catch函数中的对象属性
- jQuery使用ajax自动完成问题-TypeError:this.source不是函数
- 为什么在这种情况下,“This”确实充当javascript函数中的私有成员
- TypeError:this.getAttribute不是一个函数-javascript
- CasperJS error - undefined 不是函数 (this.waitForUrl)
- AngularJs服务函数this()
- 内联onclick函数(this)不调用jQuery方法
- jQuery自定义函数- this.each
- 为什么在构造函数'this'DOMWindow
- 调用匿名函数'this'从函数
- Javascript检查函数(this)的长度
- 如何使用onchange="函数(this.value)
- 改变一个函数"this"值
- javascript构造函数this is't绑定正确
- JS原型函数'this'混乱