Creating get/set method dynamically in javascript
Posted
by portoalet
on Stack Overflow
See other posts from Stack Overflow
or by portoalet
Published on 2010-04-11T04:32:54Z
Indexed on
2010/04/11
4:43 UTC
Read the original article
Hit count: 306
JavaScript
|object-oriented-design
I am trying to create a UserDon object, and trying to generate the get and set methods programmatically ( based on Pro Javascript book by John Resig page 37 ), and am testing this on Firefox 3.5
The problem is: in function UserDon, "this" refers to the window object instead of the UserDon object.
So after calling var userdon = new UserDon(...) I got setname and getname methods created on the window object (also setage and getage).
How can I fix this?
function UserDon( properties ) {
for( var i in properties ) {
(function(){
this[ "get" + i ] = function() {
return properties[i];
};
this[ "set" + i ] = function(val) {
properties[i] = val;
};
})();
}
}
var userdon = new UserDon( {
name: "Bob",
age: 44
});
© Stack Overflow or respective owner