The problem you are experiencing here is a problem with this
.
You are referencing this
inside of a function in a callback but the this
of that inner function refers to the parameters
object rather than the Foo
instance.
For example if you were to add after your loop this:
console.log(parameters)
I suspect you would find that the parameters
object itself was modified to have a name property with the value '50'
.
There are a couple of ways to solve this and they all have to do with preserving the correct this that you are expecting.
Use a lambda function
Alter your loop function to be a lambda function instead of a basic function like so:
parameters.forEach((e) => {
this[e.name] = e.initial;
});
The primary difference between a lambda function and a standard function is that a lambda function automatically preserves the this
of its parent scope.
Bind your function
You can also bind the function to use a specific this
rather than the default, which is the caller object.
parameters.forEach((function (e) {
this[e.name] = e.initial;
}).bind(this));
Calling .bind(obj)
on a function will return a new function where obj
is always the this
when it is called.
Capture the outer scope explicitly
Its also common to just set the this
from the outer-scope into its own variable and reference that directly.
var self = this;
parameters.forEach(function (e) {
self[e.name] = e.initial;
});
These are the basic ways to capture and use this
appropriately.
Alternative
I also want to add that other than the this
bug you are experiencing you may want to consider a different approach to your goal entirely. Specifically you may want to consider using Object.assign
to get the behavior you are looking for. This may look like this:
const f = new Foo(p)
Object.assign(f, { sensitivity: 50 })