监视JavaScript中的对象属性更改

Phi*_*ppe 37 javascript properties cross-browser object watch

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

我刚刚阅读了Mozilla的watch()方法文档.它看起来非常有用.

但是,我找不到类似于Safari的东西.Internet Explorer都没有.

如何管理跨浏览器的可移植性?

Eli*_*rey 67

刚刚创建了一个小物件.它适用于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;
    };
Run Code Online (Sandbox Code Playgroud)

  • 它仍然在Github上,我只是将它移到一个要点(https://gist.github.com/384583),因为它对于repo imo来说并不是很重要. (5认同)
  • 它是否真的适用于非DOM对象上的IE8? (3认同)