Javascript 缓存原型函数不会';t缓存它所属的对象
在Javascript中,我试图创建一个由Async.series执行的函数数组 Javascript:Javascript 缓存原型函数不会';t缓存它所属的对象,javascript,node.js,async.js,Javascript,Node.js,Async.js,在Javascript中,我试图创建一个由Async.series执行的函数数组 Javascript: function Field(name, height, width) { this.name = name; this.height = height; this.width = width; } Field.prototype.doSomething = function(callback) { console.log(name, width, height);
function Field(name, height, width) {
this.name = name;
this.height = height;
this.width = width;
}
Field.prototype.doSomething = function(callback) {
console.log(name, width, height);
// do some stuff with name, height etc. and produce someResults
callback(undefined, someResults
}
问题:
// Dict of Functions
var functions = {};
// Array of Field Objects
fields.forEach( function(field) {
functions[field.name] = field.doSomething;
}
Async.series( functions, callback );
问题是,当函数运行时,我的所有“类”变量都没有被缓存,因此在尝试以Async.series(未定义名称、宽度和高度)运行函数时会出现异常
关于如何解决这个问题,有什么想法吗?我建议使用:
否则,您的
doSomething
中的this
值就不可能是您想要的值。调用bind
将设置为调用bind
时字段的值。太棒了!非常感谢,这太完美了!
fields.forEach( function(field) {
functions[field.name] = field.doSomething.bind(field);
}