See if the object has changed

Is it possible to execute some code every time the object has changed?

var a = {x: 12, y: 63};

a.watch(function () { console.log('The object has changed!'); });

a.x = 16;   // The object has changed!
a.y = 1;   // The object has changed!

It seems to be available only for Firefox: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/watch

How can this be achieved in JavaScript / node.js? (if possible, without using the getter / setter method)

+4
source share
1 answer

You can use Object Observe ... this is experimental, so proceed with caution ...

var obj = {
    foo: 0,
    bar: 1
};

Object.observe(obj, function(changes) {
    console.log(changes);
});

obj.baz = 2;
+4
source

Source: https://habr.com/ru/post/1568729/


All Articles