JavaScript Using setters and getters to find what changed a property


Example

Let's say you have an object like this:

var myObject = {
    name: 'Peter'
}

Later in your code, you try to access myObject.name and you get George instead of Peter. You start wondering who changed it and where exactly it was changed. There is a way to place a debugger (or something else) on every set (every time someone does myObject.name = 'something'):

var myObject = {
    _name: 'Peter',
    set name(name){debugger;this._name=name},
    get name(){return this._name}
}

Note that we renamed name to _name and we are going to define a setter and a getter for name.

set name is the setter. That is a sweet spot where you can place debugger, console.trace(), or anything else you need for debugging. The setter will set the value for name in _name. The getter (the get name part) will read the value from there. Now we have a fully functional object with debugging functionality.

Most of the time, though, the object that gets changed is not under our control. Fortunately, we can define setters and getters on existing objects to debug them.

// First, save the name to _name, because we are going to use name for setter/getter
otherObject._name = otherObject.name;

// Create setter and getter
Object.defineProperty(otherObject, "name", {
    set: function(name) {debugger;this._name = name},
    get: function() {return this._name}
});

Check out setters and getters at MDN for more information.

Browser support for setters/getters:

ChromeFirefoxIEOperaSafariMobile
Version12.099.53all