Tracking modifications to a variable

I've been trying to edit $dataMap, but I've found that it's being edited by something else in the game by the time I want to reference it, essentially undoing my changes. This post isn't necessarily about $dataMap so much as being able to track it and other  variables. I'd to be able to track what function is modifying a variable, in this case $dataMap. Like a message output to the console that the variable was edited by x function.


I've heard about getters and setters in javascript, but I don't fully understand them and how I would use them in the context of this question, if they would even be useful here. Any suggestions?
Let's say you have class "Class", which contains an attribute named "attr" and you want to intercept all calls to it. You could do it like this:


Object.defineProperties(Class.prototype, {
'attr': {
get: function() { return this._attr; },
set: function(value) { this._attr = value; }
}
});


Now, whenever an object of type "Class" gets its "attr" property accessed, your getter/setter method is called, instead. You can use this to implement logging or something else. For example, i use this in my Gif plugin to intercept all calls to the internal "_bitmap" property of a Sprite/TilingSprite, so i can return the currect bitmap depending on the animation frame.


/edit: You could as well use Object.defineProperty in this case, which is more suited for single properties. I tend to use defineProperties for everything, since it's easy to append new properties and i think it seems cleaner to always use the same function. No idea, how this works out, performance-wise, but it's only called once at game start, anyway.
Thank you, that was very informative! Hmm, I tried $dataMap with this, but I got an error: "Uncaught TypeError: Object.defineProperties called on non-object"
Probably because $dataMap didn't exist at that point. It gets set during DataManager.loadMapData. If you are only interested at that specific object, you may as well extend that method.

Original thread: https://forums.rpgmakerweb.com/threads/tracking-modifications-to-a-variable.59231/