2013-12-10 44 views
0

在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); 
    // 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中(名称,宽度和高度未定义)。

有关如何解决此问题的任何想法?

回答

2

我会建议使用bind

fields.forEach(function(field) { 
    functions[field.name] = field.doSomething.bind(field); 
} 

,否则没有机会的thisdoSomething里面的值将是你想要的。在调用bind时调用bindthis设置为field的值。

+0

令人惊叹!非常感谢,这是完美的! –