Object.create
2018-09-05 本文已影响7人
阿畅_
语法: Object.create(proto,[propertiesObject])
参数: proto -> 一个对象,作为新创建对象的原型
propertiesObject 可选。如果没有指定为 undefined,则要添加到新创建对象的可枚举属性(即其自身定义的属性,而不是原型链上的枚举属性)对象的属性描述以及相应的属性名称。这些属性对应 Object.defineProperties() 的第二个参数。
返回值: 一个新对象,带着指定的原型对象和属性。
另外: 如果 propertiesObject 参数不是 null 或者一个对象,则抛出一个 TypeError 异常。
const person = {
live: true,
initFunction: function () {
console.log(`My name is ${this.name}. Do you like your life now? ${this.live}`)
}
}
person.name = '阿畅'
person.live = false
person.initFunction();
My name is 阿畅. Do you like your life now? false
const newPerson = Object.create(person)
newPerson.name = '我迎着风'
newPerson.initFunction()
My name is 我迎着风. Do you like your life now? false
- Object.create() 的原理 用原生的 JavaScript 模拟一下原理
function newObject(O) {
function fn() {
}
fn.prototype= O;
return new fn;
}
const newPer = newObject(person)
newPer.name = '自己创建的 Object';
newPer.initFunction()
My name is 自己创建的 Object. Do you like your life now? false