标签:
方式1
使用Object.defineProperty定义单个属性
‘use strict‘; var person = { }; // 定义数据属性 Object.defineProperty(person, ‘_age‘, { configurable: true, writable: true, enumerable: true, value: -1, }); // 定义访问器属性 Object.defineProperty(person, ‘age‘, { configurable: false, enumerable: false, get: function () { return this._age; }, set: function (newValue) { if (newValue <= 0 || newValue > 100) { this._age = 18; } else { this._age = newValue; } } }); // -1 console.log(person.age); person.age = 0; // -18 console.log(person.age); person.age = 30; // 30 console.log(person.age);
方式2
使用Object.defineProperties方法定义多个属性
‘use strict‘; var person = { }; Object.defineProperties(person, { _age: { configurable: true, writable: true, enumerable: true, value: -1, }, age: { configurable: false, enumerable: false, get: function () { return this._age; }, set: function (newValue) { if (newValue <= 0 || newValue > 100) { this._age = 18; } else { this._age = newValue; } } } }); // -1 console.log(person.age); person.age = 0; // -18 console.log(person.age); person.age = 30; // 30 console.log(person.age);
标签:
原文地址:http://www.cnblogs.com/loftyspirit/p/5770725.html