value, writable, enumerable, configurable
get, set, enumerable, configurable
Object.defineProperty(obj, prop, descriptor)
Object.defineProperties(obj, props)
Object.getOwnPropertyDescripter(obj, prop)
Object.getOwnPropertyDescripters(obj)
let obj2 = {
_name: 'zty',
get name() {
return this._name
},
set name(name) {
this._name = name + '1'
}
}
obj2.name // "zty"
obj2.name = 'zzx'
obj2.name // "zzx1"
Object.getOwnPropertyDescriptor(obj2, 'name')
{
configurable: true,
enumerable: true,
get: ƒ name(),
set: ƒ name(name)
}
Object.getOwnPropertyDescriptor(obj2, '_name')
{
configurable: true,
enumerable: true,
value: "zzx1",
writable: true
}
Object.getOwnPropertyDescriptors(obj2)
{
name: {
configurable: true,
enumerable: true,
get: ƒ name(),
set: ƒ name(name)
},
_name: {
configurable: true,
enumerable: true,
value: "zzx1",
writable: true
}
}
let obj = {}
obj.key1 = 'value1'
let descriptor = Object.create(null)
descriptor.value = 'value2'
Object.defineProperty(obj, 'key2', descriptor)
Object.getOwnPropertyDescriptors(obj)
{
key1: {value: "value1", writable: true, enumerable: true, configurable: true},
key2: {value: "value2", writable: false, enumerable: false, configurable: false}
}
// 也就是说
o.a = 1;
// 等同于 :
Object.defineProperty(o, "a", {
value : 1,
writable : true,
configurable : true,
enumerable : true
});
// 另一方面,
Object.defineProperty(o, "a", { value : 1 });
// 等同于 :
Object.defineProperty(o, "a", {
value : 1,
writable : false,
configurable : false,
enumerable : false
});