Skip to content

Instantly share code, notes, and snippets.

@patrickgalbraith
Created September 4, 2014 05:54
Show Gist options
  • Star 16 You must be signed in to star a gist
  • Fork 6 You must be signed in to fork a gist
  • Save patrickgalbraith/9538b85546b4e3841864 to your computer and use it in GitHub Desktop.
Save patrickgalbraith/9538b85546b4e3841864 to your computer and use it in GitHub Desktop.
Javascript dynamic getter, setter using defineProperty
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);
@Akronae
Copy link

Akronae commented Sep 21, 2019

This helped me overwrite a get only property of a vue component I get no control over, thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment