Object.defineProperty()方法定义一个新属性,或者修改对象上的现用属性,并返回对象
Object.defineProperty(obj, prop, descriptor)
Parameters
obj
- 对象
prop
- 需要改变或定义的对象的属性
descriptor
- 描述
Return value
定义或改变后的对象
descriptor中的定义的key介绍:
configurable
true
可以删除定义的属性
Defaults to false.enumerable
true
可以对定义的属性进行枚举
Defaults tofalse
.
value
- 设置属性的值
Defaults toundefined
. writable
true
定义属性值可以被改变
Defaults tofalse
.
An accessor descriptor also has the following optional keys:
get
- 函数返回将用作属性的值
Defaults toundefined
. set
- 该函数将作为唯一的参数接收到被分配给属性的新值.
Defaults toundefined
. -
创建一个属性:
///第一种方法 var o = {}; // 创建一个新的对象 Object.defineProperty(o, 'a', { value: 37, writable: true, enumerable: true, configurable: true }); ///第二种方法 var bValue = 38; Object.defineProperty(o, 'b', { get: function() { return bValue; }, set: function(newValue) { bValue = newValue; }, enumerable: true, configurable: true }); o.b; // 38
Writable
var o = {}; Object.defineProperty(o, 'a', { value: 37, writable: false }); console.log(o.a); // logs 37 o.a = 25; console.log(o.a); // logs 37. writable为false,不可改变
Enumerable 可序列属性
var o = {}; Object.defineProperty(o, 'a', { value: 1, enumerable: true }); Object.defineProperty(o, 'b', { value: 2, enumerable: false }); Object.defineProperty(o, 'c', { value: 3 }); o.d = 4; for (var i in o) { console.log(i); } // logs 'a' and 'd' (in undefined order) Object.keys(o); // ['a', 'd'] o.propertyIsEnumerable('a'); // true o.propertyIsEnumerable('b'); // false o.propertyIsEnumerable('c'); // false