JS中监控对象属性的方法

原创
2019/07/08 15:10
阅读数 237

步骤1:在运行所需监控的代码前引入以下代码

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;
    };

步骤2:定义所需监控的对象和属性,并定义hook方法(hook方法对应上文代码中的handler.call(this, prop, oldval, val));如监控document中的cookie属性,则可以使用以下代码

document.watch("cookie", function (prop, oldVal, newVal) {
 console.log("prop:" + prop);
 console.log("old val:" + oldVal);
 console.log("new val:" + newVal);
 return newVal;
})

步骤3:运行相关代码就会进入hook代码中

展开阅读全文
加载中

作者的其它热门文章

打赏
0
0 收藏
分享
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部