質問

In Javascript I'm trying to make an array of functions to be executed by 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
}

Problem:

// Dict of Functions
var functions = {};

// Array of Field Objects
fields.forEach( function(field) {
  functions[field.name] = field.doSomething;
}

Async.series( functions, callback );

The problem is that all my "class" variables aren't cached when the function is so I get exceptions when trying to run the function in Async.series (name, width and height are not defined).

Any ideas on how I can get around this?

役に立ちましたか?

解決

I would suggest using bind:

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

Otherwise, there is no chance that the value of this inside your doSomething is going to be what you want. Calling bind sets this to the value of field at the time bind is called.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top