JS 物件的訪問器屬性的使用
阿新 • • 發佈:2019-01-01
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
好好體會