5.3Object.create()
【1】定义:基于一个现有父对象,创建一个新的子对象继承父对象
【2】何时使用:如果想创建一个子对象继承父对象,但是有没有构造函数就不能使用new,这时使用Object.create()
【3】如何使用:
var 新子对象=Object.create(父对象, {
//给子对象添加自有属性
//必须用defineProperties函数相同的格式:
属性名:{
value:属性值,
writable:true,
enumerable:true,
configurable:false
},
... : { ... }
})
【4】工作,共做了3件事
a. 创建新对象
b. 设置新对象继承父对象
c. 强行为新对象添加自有属性
【5】示例
var father={
money:10000000000,
car:"infiniti"
}
// 创建子对象,让子对象继承父对象,但是子对象本身是空的
var child=Object.create(father);
child.bag="LV1";
console.log(child);
// 创建子对象,让子对象继承父对象的同时,为子对象添加自有属性
var child1=Object.create(father,{
phone:{
value:"小米11",
writable:true,
enumerable:false,
configurable:false
},
bag:{
value:"LV",
writable:true,
enumerable:true,
configurable:false
}
})
console.log(child1);