While searching the web, I've encountered a post that shows why the following example of dynamically generated methods does not work as planned:
// Create a new user object that accepts an object of properties
function User( properties ) {
// Iterate through the properties of the object, and make sure
// that it's properly scoped (as discussed previously)
for ( var i in properties ) { (function(){
// Create a new getter for the property
this[ "get" + i ] = function() {
return properties[i];
};
// Create a new setter for the property
this[ "set" + i ] = function(val) {
properties[i] = val;
};
})(); }
}
The reason for that is the anonymous function, which uses the "this" keyword is context of the "window", instead of "User".
1) Why does the this keyword in the anonymous function refers to "window instead of "User"?
2) Is there an accepted and common way to create "Dynamically Generated Methods"?
Thanks,
Joel