Snippets: An impressive, obscure JavaScript trick
1 min readNov 3, 2016
tl;dr: Object.defineProperty lets you intercept reads and writes on POJO object properties (I know, crazy, right?).
When and why would I use this?
- The variable you set a few lines ago mysteriously gets changed, and you have no idea what’s changing it. What the heck is going on?
- A variable is being modified everywhere in the code, but sometimes it gets set with an unwanted value. You’d like to print a stack trace at the point when the unwanted value is set.
Sample snippets of code
- I’ve put together a quick JSFiddle “video” that shows you how it works in action. Click here to watch it.
- The following snippet should give you an idea of what this technique is capable of doing.
// You can open up your console and paste this snippet as-is
// Our POJO object
var foo = {bar: "baz"};// Here, we initialize the interceptors
Object.defineProperty(foo, 'bar', {
set: function(value) {console.trace("set", value);},
get: function() {console.trace("get");}
});// the following lines all print stack tracesvar king = foo.bar; // stack trace on GET foo.bar
var leonidas = foo.bar; // stack trace on GET foo.barfoo.bar = 300; // stack trace on SET foo.bar
foo.bar = "sparta"; // stack trace on SET foo.bar
Links
Object.defineProperty can do a lot more than what I’ve described here. Read more about it on Mozilla’s website.