Using setters and getters to find what changed a property

suggest change

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:

| Chrome | Firefox | IE | Opera | Safari | Mobile |

|———|––––|———|––|—––|––––|––––| | Version | 1 | 2.0 | 9 | 9.5 | 3 | all |

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


Debugging:
* Using setters and getters to find what changed a property

Table Of Contents
11 Arrays
12 Objects
14 Classes
16 Map
17 Set
24 Loops
27 Date
29 Scope
30 AJAX
35 Cookies
41 JSON
44 Fetch
45 Modules
46 Screen
51 Debugging
64 Console
68 Symbols
73 Modals
76 Events
86 Proxy
89 WeakMap
90 WeakSet
102 Tilde