在Proxy没有标准化之前,FF的Object.prototype.watch可是一个好东西。通过ecma262v5的特性描述符,我们可以实现此功能,这用于node.js最好不过了。
if ( ! Object.prototype.watch) { Object.defineProperty(Object.prototype, 'watch', { value: function (prop, handler) { var val = this[prop]; var getter = function () { return val; }; var setter = function (newVal) { var val = handler.call(this, prop, val, newVal); }; if (delete (this[prop])) { Object.defineProperty(this, prop, { get: getter, set: setter, configurable: true }); } } }); } /** * Object.unwatch() - Removes a watchpoint set with the watch method. * @param prop */ if ( ! Object.prototype.unwatch) { Object.defineProperty(Object.prototype, 'unwatch', { value: function (prop) { var val = this[prop]; delete (this[prop]); this[prop] = val; } }); }