使用Object.getOwnPropertyDescriptor方法读取属性特征
‘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; } } } }); var descriptor1 = Object.getOwnPropertyDescriptor(person, ‘_age‘); // true console.log(descriptor1.configurable); // true console.log(descriptor1.writable); // true console.log(descriptor1.enumerable); // -1 console.log(descriptor1.value); var descriptor2 = Object.getOwnPropertyDescriptor(person, ‘age‘); // false console.log(descriptor2.configurable); // false console.log(descriptor2.enumerable); // [Function] console.log(descriptor2.get); // [Function] console.log(descriptor2.set);
时间: 2024-10-09 06:38:44