Let there be an object userSingleton
defined as such:
var userSingleton = new function() {
var _user = undefined;
Object.defineProperty(this, 'activeUser', {
get: function() {
console.log("Getter called, done something cool");
return _user;
},
set: function(val) {
console.log("Setter called, do something cooler");
_user = val;
}
});
}
Now if I go to use it, userSingleton.activeUser = {name: 'John Doe'};
works great! I get a "Setter called, do something cooler".
However, if I try to do userSingleton.activeUser.name = 'John Doe';
I instead get a "Getter called, done something cool" and userSingleton._user
is not updated.
What's happening is it's trying to set the name
property of the object returned by the getter (userSingleton.activeUser
).
How do I make it call a particular function when any (unknown at definition time) property is assigned to / modified?