/* * 對象屬性保護 * 方式1 * */ { function Person() { var data ={ name:'lee', age:18, sex:'0' } this.get = function (key) { return data.key } this.set = function (key,value) { if (!key == sex){ data.key = value } } } var person = new Person(); //sex屬性受保護 } /* * 方式2 * defineProperty * */ { var person = { name:'lee', age:18 } Object.defineProperty(person,'sex',{ //定義一個sex屬性,設置爲只讀屬性 writable:false, value:0 }) } /* * 方式3 * 對象代理 * */ { let person = { name:'lee', age:18, sex:0 } let p = new Proxy(person,{ get(target,key){ return target.key }, set(target,key,value){ if (key !== 'sex'){ target.key = value } } }) //p.sex = 1; }