JS 对象的访问器属性的使用

var person = {
    color : "yellow",
    sex : "male",
    age : 25
};

function defineReactive(obj, key, val) {
    Object.defineProperty(obj, key, {
        get : function () {
            console.log("read data: " + val);
            return val;
        },
        set : function (newVal) {
            console.log("set data : " + newVal);
            val = newVal;
        }
    })
}

Object.keys(person).forEach(function (key) {
     defineReactive(person, key, person[key])
});
console.log("person color:" + person.color);
console.log("person age:" + person.age);

Good 

======================================================================================

var person = {
    color : "yellow",
    sex : "male",
    age : 25
};

Object.keys(person).forEach(function (key) {
     Object.defineProperty(person, key, {
         get : function () {
             console.log("read data");
             return person[key];
         },
         set : function (newVal) {
             console.log("set data:" + newVal);
             person[key] = newVal;
         }
     })
});

console.log("person color:" + person.color);

Not Good 

好好体会

猜你喜欢

转载自blog.csdn.net/liubangbo/article/details/85267311
今日推荐