Say I have the following object definition:
var car = function (engine) {
this.engine = engine;
this.calculateSpeed = function () {
return engine.power * 20;
};
};
the engine
object in the calculateSpeed()
function refers to the engine object passed in via the constructor and not the car's public engine member(which is the one I want).
If I wanted to change the engine of the car after creating the car object I want the calcuateSpeed()
function to reference the new engine.
The Inner function cannot access outer functions variable question is similar to mine. But does not quite cover my use case as the OP is using a local variable and has no constructor.
If you could also explain why this won't work, that would also help a lot:
var car = function (engineInit) {
this.engine = engineInit;
this.calculateSpeed = function () {
return engine.power * 20;
};
};
I know for this simple example I could use this.calculateSpeed = engine.power * 20;
but for my real use case, I need a function.