JavaScript 对象的方法
create 初始化
![在这里插入图片描述](https://img-blog.csdnimg.cn/da6c58f4a1894ac49bb96e38038967d8.png?x-oss-process=image/watermark,type_d3F5LXplbmhlaQ,shadow_50,text_Q1NETiBA5oiR5Y-q5piv5LiA5Liq5bCP5bCP5YmN56uv,size_7,color_FFFFFF,t_70,g_se,x_16)
使用create创建对象,传入null没有任何属性,没有继承Object上的任何属性
传入{}创建对象,继承了Object上的属性,挂载在Object的原型链上
assign 浅拷贝
let obj = {name:'李白',list:[1,2,3,4],obj:{list:[1,2,3,4]}}
let obj1 = Object.assign({},obj)
obj.list = [1,2]
obj.obj.list = [1,2]
defineProperty 给对象添加或修改一个属性
var obj = {}
Object.defineProperty(obj,'name',{
value: 'xxx',
writable: false,
configurable: false,
enumerable: false
})
var obj = {}
Object.defineProperty(obj,'name',{
get(val){
console.log(val,'get')
},
set(val){
console.log(val,'set')
},
})
obj.name = 'xxx'
defineProperties 给对象添加或修改多个属性
var obj = {}
Object.defineProperties(obj,{
name:{
value:'xxx'
}
})
keys、values、entries 、fromEntries 获取对象的键、值
var obj = {name:'xxx',age:24}
Object.keys(obj)
Object.values(obj)
Object.entries (obj)
var entries = [['name', 'xxx'],['age', 24]]
var obj1 = Object.fromEntries(entries);
freeze 冻结 isFrozen 判断方法是否被冻结
var obj = {name:'xxx'}
var obj1 = Object.freeze(obj)
obj1.name = 'eee'
obj.name = 'hhh'
Object.isFrozen(obj)
getOwnPropertyDescriptor 获取对象属性上的描述符的值
var obj = {name:'xxx'}
var a = Object.getOwnPropertyDescriptor(obj,'name')
console.log(a.value)
console.log(a.writable)
console.log(a.configurable)
console.log(a.enumerable)
getOwnPropertyDescriptors 获取一个对象的所有属性的描述符
var obj = {
name:'xxx'
}
Object.getOwnPropertyDescriptors(obj)
getOwnPropertyNames 通过一个数组返回一个对象的所有属性(可枚举及不可枚举)
var obj = {name:'xxx',age:24}
Object.getOwnPropertyNames (obj)
getPrototypeOf 返回对象的原型
const a= {};
const obj = Object.create(a);
console.log(Object.getPrototypeOf(obj) === a);
is 判断两个值是否相等
var a = 1,b = true
a == b
a === b
Object.is(a,b)
isExtensible // 指定值是否可以添加属性 isSealed // 判断一个对象是否是密封的(不可添加属性)
const obj= {};
console.log(Object.isExtensible(obj));
Object.preventExtensions(obj);
console.log(Object.isExtensible(obj));
Object.isSealed(obj)
preventExtensions
seal 阻止添加属性
var obj = {}
obj.name = 'xxx'
Object.seal(obj)
obj.age = 24
setPrototypeOf 给对象添加原型
function a(){}
var b = {}
Object.setPrototypeOf(b,new a())