Forked from patrickgalbraith/gist:9538b85546b4e3841864
Created
January 22, 2021 13:55
-
-
Save lon9man/2532d5e476b1c1d737589b342da4604e to your computer and use it in GitHub Desktop.
Javascript dynamic getter, setter using defineProperty
This file contains 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