As @ChadMcGrath pointed out Object.observe
is probably what you want, but some other options are available, for example if a variable is a property on an object you could define a setter for it:
var o = {};
Object.defineProperty(o, "myProperty",{
set: function (x) {
console.log("Set myProperty to", x);
console.trace();
this.value = x;
},
get: function () {
return this.value;
},
});
With ECMAScript 2015 you can use a Proxy
, but this doesn't work in most browsers yet:
var handler = {
set: function(target, name, value, receiver){
console.log("Set", name, "to", value);
console.trace();
target[name] = value;
}
};
var o = new Proxy({}, handler);
o.myProperty = 1; //Will console log and give you a trace.