Action: Set the value of object properties, object properties or modify the value of the object and returns.
Object.defineProperty(obj, prop, descriptor)
- obj: Object Name
- : prop property name to be set
- descriptor: to be defined or modified attribute descriptor, the parameter is an object that the value of the common set of four attributes.
1. value:属性对应的值 2. writeable:该属性是否可以被重写。 3. configurable:控制第三个参数对象中其他的属性是否能改变,只有为true 的时候,其他值(value ,writeable,enumerable)的值才能被改变,对象的该属性才能被删除。 4. enumerable:只有该值为 true 的时候该属性才能被枚举出来。
<script>
var obj = { name: '123', age: 18 }
Object.defineProperty(obj, 'name', {
value: 'zs',
writable: false,
configurable: true,
enumerable: false
})
console.log(obj) // {age: 18, name: "zs"}
// 如果对象设置了defineProperty,只有在 writable 的值为 true 的时候才能通过 点 的方式修改属性值
obj.name = 'hhh'
console.log(obj) // {age: 18, name: "zs"}
// 如果对象设置了defineProperty,只有在 configurable 的值为 true 才能删除该属性
delete obj.name
console.log(obj) // {age: 18}
// 如果对象设置了defineProperty,只有在 configurable 的值为 true 才能通过 value 方式重新赋值
bject.defineProperty(obj, 'name', {
value: 'hhh'
})
console.log(obj) // {age: 18, name: "hhh"}
// 只有当 enumerable 为true 的时候才能被枚举出来
console.log(Object.keys(obj)) // ["age"]
</script>