属性描述符数组
操做对象元属性函数
特性名称 | 描述 | 默认值 |
---|---|---|
value | 设置属性的值 | undefined |
writable | 设置是否可修改值 | true |
enumerable | 表示可否经过 for-in 或 obj.keys()循环返回属性。 | true |
configurable |
|
true |
var obj = { test: 'hello', }; //默认状况下 var desc = Object.getOwnPropertyDescriptor(obj, 'test'); console.log(desc); // desc = { // configurable: true, // enumerable: true, // value: 'hello', // writable: true, // }
使用 对象字面量 建立的属性,writable、enumerable 和 configurable 特性默认为 true。this
特性名称 | 描述 | 默认值 |
---|---|---|
Get | 在读取属性时调用的函数 | undefined |
Set | 在写入属性时调用的函数 | true |
enumerable | 属性是否能够被枚举(使用 for...in 或 Object.keys()) | true |
configurable |
|
true |
var obj = { $n: 5, get next() { return this.$n++; }, set next(n) { if (n >= this.$n) this.$n += n; else throw new Error('新的值必须大于当前值'); }, }; obj.next = 6 console.log(obj.$n);
语法:code
Object.defineProperty(obj, prop, descriptor)
参数列表:对象
obj:必需。目标对象 prop:必需。需定义或修改的属性的名字 descriptor:必需。目标属性所拥有的特性
返回值:ip
传入函数的对象。即第一个参数obj
var obj = {}; Object.defineProperty(obj, 'name', { get: function() { return this._name; //在 get 和 set 中使用访问属性必须加 "_" }, set: function(val) { if (Array.isArray(val)) { this._name = val; } else { this._name = '不是数组不能赋值'; } }, enumerable: true, // 表示可枚举的 configurable: true, // 是否可删除属性 }); // Object {get: function, set: function, enumerable: true, configurable: true} console.log(Object.getOwnPropertyDescriptor(obj, 'name')); obj.name = '111'; console.log(obj.name);
var obj = {}; Object.defineProperties(obj, { name: { value: '周华健', writable: true, }, age: { value: 30, writable: true, }, sex: { get: function() { return this._sex; }, set: function(val) { if (val === 1) { this._sex = '男'; } else { this._sex = '女'; } }, }, }); obj.sex = 0; console.log(obj.sex); //女
参数:get
属性所在的对象和要读取其描述符的属性名称
返回值:it
//存取属性 Object { configurable 、 enumerable 、 get 和 set} //数据属性 Object {configurable 、 enumerable 、 writable 和 value}
var obj = { name: 'Timo', }; obj.sex = 'woman'; // 获取单个属性的描述符 var desc = Object.getOwnPropertyDescriptor(obj, 'sex'); // 获取多个属性的描述符 var descs = Object.getOwnPropertyDescriptors(obj); console.log(desc); console.log(descs);