先实现一个简单的数据劫持。
思路:

  1. 遍历对象的每个属性,为每个属性挂上监听函数(即利用Object.defineProperty进行元编程);

  2. 考虑属性的子属性的监听;
    先上代码:


function Observer(data) {
    this.data = data;
    this.walk(data);
}
Observer.prototype.walk = function(obj) {
    var val;
    for (var key in obj) {
        if (obj.hasOwnProperty(key)) {
            val = obj[key];

            if (obj[key] instanceof Object) {
                new Observer(obj[key]);
            }

            this.convert(key, val);
        }
    }
}
Observer.prototype.convert = function(key, val) {
    Object.defineProperty(this.data, key, {
        enumerable: true,
        configurable: true,
        get: function() {
            console.log('你访问了' + key);
            return val;
        },
        set: function(newVal) {
            console.log('你设置了' + key);
            console.log('新的' + key + '=' + newVal);
            if (val === newVal) {
                return;
            }
            val = newVal;
        }
    });
}
var data = {
    user: {
        name: "lixixi",
        age: "24"
    },
    address: {
        city: "beijing"
    }
};

var app = new Observer(data);

其中涉及的知识点:

  1. Object.defineProperty(object, key, {});

  2. 如果属性值还是对象,则递归继续new Observer;


Alex
58 声望3 粉丝