2

I have an object, let's call it obj, it looks like this:

const obj = {
  key: "value"
}

Now I want to do something when a property is set. I heard about setters, that I can use by doing:

const obj = {
   set key(e) {
     console.log("Property key has been set!")
   }
}

But I want to do this, for any property... Like instead of only for key, it would be for anything, example:

obj.SomeKey = "value"

Should log "Property key has been set!" and it would be the same for any property... Is there a way in JavaScript to do this? Thanks

demo
  • 159
  • 2
  • 11
  • 1
    Read on [Proxy](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy)! – pishpish Mar 16 '19 at 09:48

1 Answers1

2

You could create a ES6 Proxy, which allows you to modify the set method like so:

const obj = {
  key: "value"
};

const objProxy = new Proxy(obj, {
  set: (obj, prop, v) => {
    obj[prop] = v;
    console.log("do something");
  }
});

objProxy.name = "foo";
console.log(objProxy); // Proxy now has name attribute
console.log(obj); // And so does the original object
Nick Parsons
  • 45,728
  • 6
  • 46
  • 64