观察对象是否已更改

时间:2014-12-23 10:32:14

标签: javascript node.js object.observe

每次对象更改时,是否可以执行一些代码

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!

它似乎仅适用于Firefox:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/watch

如何在JavaScript / node.js中实现这一点?(如果可能,不使用getter / setter方法)

1 个答案:

答案 0 :(得分:4)

你可以使用Object Observe ......它的实验,所以请谨慎行事......

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

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

obj.baz = 2;