前言
简单记录一下 ES5 Object.defineProperty的使用
示例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
| const obj = { name: "hello world", age: 12 };
Object.defineProperty(obj, "$name", { configurable: false, enumerable: true, get:function (){ console.log('获取', obj.name); return obj.name; }, set:function (value){ console.log('设置$name为:', value); obj.name = value; } });
let test = obj; test.$name = 'xxx';
console.log(obj.$name); console.log(obj); console.log(test);
|