"Esto" dentro de una función anónima?
n el libro de John Resig "Técnicas Pro Javascript", describe una forma de generar métodos de objetos dinámicos con el siguiente código:
// 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;
};
})();
}
}
El problema es cuando intento crear instancias del objeto anterior, los métodos dinámicos se unen al objeto de la ventana en lugar del objeto instanciado. Parece que "esto" se refiere a la ventana.
// Create a new user object instance and pass in an object of
// properties to seed it with
var user = new User({
name: "Bob",
age: 44
});
alert( user.getname() );
Ejecutar el código anterior arroja este error "user.getname no es una función".
Cuál es la forma correcta de generar las funciones dinámicas para cada objeto instanciado?