Forked from patrickgalbraith/gist:9538b85546b4e3841864
Created
October 20, 2019 09:58
-
-
Save guerrerocarlos/28ea567af8c8b071d8a97423b8631c39 to your computer and use it in GitHub Desktop.
Javascript dynamic getter, setter using defineProperty
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var User = (function () { | |
function User (id, nam) { | |
var self = this; | |
this.id = id; | |
this.nam = nam; | |
this.__data = {}; | |
for(var p in self) { | |
if(p === '__data') { | |
return; | |
} | |
self.__data[p] = self[p]; | |
(function(field_name) { | |
Object.defineProperty (self, field_name, { | |
get: function () { | |
console.log('GET', field_name); | |
return self.__data[field_name]; | |
}, | |
set: function (new_value) { | |
console.log('SET', field_name, new_value); | |
self.__data[field_name] = new_value; | |
self.__data['modified'] = (new Date()).getTime(); | |
} | |
}); | |
})(p); | |
} | |
}; | |
return User; | |
}) (); | |
var user1 = new User(1, "Paul"); | |
var user2 = new User(2, "Mark"); | |
console.log(user1.id); | |
user1.id = 5; | |
console.log(user1.id); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment