用法:Object.defineProperty()定义新属性或修改原有的属性
语法:Object.defineProperty(obj,prop,descriptor)
Object.defineProperty() 第三个参数 descriptor 说明:以对象形式{ } 书写:
- value: 设置属性的值, 默认值为undefined
- writable: 值是否可以重写。 true|false 默认为false
- enumerable: 目标属性是否可以被枚举。true|false 默认为flase
- configurable: 目标属性是否可以被删除或是可以再次修改特性 true|false 默认为false
举个例子:
var obj = {
id: 1,
name: '红米手机',
price: '1999'
}
1.修改对象里面的属性
Object.defineProperty(obj,'price',{
value: 999
})
console.log(obj) // 得到: {id: 1, name: "红米手机", price: 999}
2.往对象里面添加属性
Object.defineProperty(obj,'num',{
value: 10
})
console.log(obj) // 得到: {id: 1, name: "红米手机", price: 999, num: 10}
3.如果 writable:false,则不允许修改
Object.defineProperty(obj,"id",{
writable:false
})
obj.id = 2;
console.log(obj) // 得到:writable:false {id: 1, name: "红米手机", price: 999}
4.如果 writable:true,则keyi修改
Object.defineProperty(obj,"id",{
writable:true
})
obj.id = 2;
console.log(obj) // 得到: writable:true {id: 2, name: "红米手机", price: 999}
5.如果enumerable 值为false 则不允许遍历,默认值为false
Object.defineProperty(obj,"id",{
writable:true,
enumerable:false
})
console.log(Object.keys(obj)); // 得到: ["name", "price"]
6.如果enumerable 值为true 则允许遍历,默认值为false
Object.defineProperty(obj,"id",{
writable:true,
enumerable:true
})
console.log(Object.keys(obj)); //["id", "name", "price"]
7.如果configurable 值为false, 则不允许删除或者修改特性
Object.defineProperty(obj,"price",{
writable:true,
enumerable:true,
configurable: false
})
delete obj.price;
console.log(Object.keys(obj)); // ["id", "name", "price"]
8.如果configurable 值true, 则允许删除或者修改特性
Object.defineProperty(obj,"price",{
writable:true,
enumerable:true,
configurable: true
})
delete obj.price;
console.log(Object.keys(obj)); // ["id", "name"]
目前大概就是这些
建议:眼看千遍,不如手敲一遍
网友评论