观察JavaScript中的对象属性更改

可能重复:
所有浏览器的Javascript Object.Watch?

我只是阅读Mozilla的watch()方法的文档。 它看起来非常有用。

不过,我找不到类似的Safari。 无论是Internet Explorer。

你如何pipe理浏览器的可移植性?

我不久前创造了一个小物件 。 它适用于IE8,Safari,Chrome,Firefox,Opera等。

/* * object.watch v0.0.1: Cross-browser object.watch * * By Elijah Grey, http://eligrey.com * * A shim that partially implements object.watch and object.unwatch * in browsers that have accessor support. * * Public Domain. * NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK. */ // object.watch if (!Object.prototype.watch) Object.prototype.watch = function (prop, handler) { var oldval = this[prop], newval = oldval, getter = function () { return newval; }, setter = function (val) { oldval = newval; return newval = handler.call(this, prop, oldval, val); }; if (delete this[prop]) { // can't watch constants if (Object.defineProperty) // ECMAScript 5 Object.defineProperty(this, prop, { get: getter, set: setter }); else if (Object.prototype.__defineGetter__ && Object.prototype.__defineSetter__) { // legacy Object.prototype.__defineGetter__.call(this, prop, getter); Object.prototype.__defineSetter__.call(this, prop, setter); } } }; // object.unwatch if (!Object.prototype.unwatch) Object.prototype.unwatch = function (prop) { var val = this[prop]; delete this[prop]; // remove accessors this[prop] = val; }; 

不幸的是,这不是一个便携式解决scheme。 IE没有这样的东西,据我所知,虽然如果有的话,它会很棒

你也许可以通过覆盖方法和variables来实现你自己的notifcation系统。 虽然我不认为这是至关重要的,但我不知道你计划如何做这样一个系统。