The this
value you are using belongs to the auto-invoking function expression you have inside the loop, and when you invoke a function in this way, this
will always refer to the global object.
Edit: I missed the fact that the function expression is trying to make variable capturing to handle the getter/setter creation inside the loop, but the looping variable i
, needs to be passed as an argument in order to do it and since the function expression is there, context (the outer this
) should be preserved:
function UserDon( properties ) {
var instance = this; // <-- store reference to instance
for( var i in properties ) {
(function (i) { // <-- capture looping variable
instance[ "get" + i ] = function() {
return properties[i];
};
instance[ "set" + i ] = function(val) {
properties[i] = val;
};
})(i); // <-- pass the variable
}
}
var userdon = new UserDon( {
name: "Bob",
age: 44
});
userdon.getname(); // "Bob"
userdon.getage(); // 44
You can also use the call
method to invoke the function expression, preserving the context (the value of this
) and introducing the looping variable to the new scope in a single step:
function UserDon( properties ) {
for( var i in properties ) {
(function (i) { // <-- looping variable introduced
this[ "get" + i ] = function() {
return properties[i];
};
this[ "set" + i ] = function(val) {
properties[i] = val;
};
}).call(this, i); // <-- preserve context and capture variable
}
}
I would also recommend to use an if (properties.hasOwnProperty(i)) { ... }
inside the for...in
loop to avoid iterating over user extended properties inherited from Object.prototype
.