I\'m reading \"Pro Javascript Techniques\" from John Resig, and I\'m confused with an example. This is the code:
// Create a new user object that accepts an
I found something that seems to be the answer, its all about context. Using the anonymous function inside the for, changes the context making 'this' refer to the window object, strange isn't it?
so:
function User( properties ) {
for ( var i in properties ) {
// here this == User Object
(function(){
// inside this anonymous function this == window object
this[ "get" + i ] = function() {
return properties[i];
};
this[ "set" + i ] = function(val) {
properties[i] = val;
};
})();
}
}
I don't know why that function changes the context of execution, I'm not sure it should do that, anyway you can test it running the code there and trying window.getname() and it magically works! :S
The solution as sated before is changing the context, it can be done like J Cooper said, passing the variable 'me' and making the function a closure or you can do this:
(function(){
// inside this anonymous function this == User because we called it with 'call'
this[ "get" + i ] = function() {
return properties[i];
};
this[ "set" + i ] = function(val) {
properties[i] = val;
};
}).call(this);
Anyway, I'm still getting 44 when running 'getname'... any ideas?
you probably want something like this, which is more readable: (closures are easy to learn once you get some practice)
function User( properties ) {
// helper function to create closures based on passed-in arguments:
var bindGetterSetter = function(obj,p,properties)
{
obj["get"+p]=function() { return properties[p]; }
obj["set"+p]=function(val) { properties[p]=val; return this; }
};
for (var p in properties)
bindGetterSetter(this, p, properties);
}
I also added "return this;" so you can do:
u=new User({a: 1, b:77, c:48});
u.seta(3).setb(20).setc(400)