Object.create

2020-03-24  本文已影响0人  hello_water
用法
Object.create(obj);

创建一个新对象。使用现有对象来提供新创建对象的proto

解析
var person={
    isMan:false,
    printInfo:function(){
        console.log(`My name is ${this.name}.I am ${this.isMan?'man':'female'}.`)
    }
}

var me = Object.create(person);

person.isMan === me.isMan;//true
person.printInfo === me.printInfo;//true

person.isMan=true;
console.log(me.isMan);//true

me.isMan=false;
me.name='marry';
console.log(me.printInfo());//My name is marry.I am female.

结论是 现有对象和新对象的原型指向同一份数据,修改会使现有对象和新对象同时生效。

//创建空的object,不设定_proto_
var test=Object.create(null);
console.log(test._proto_);//undefined
上一篇 下一篇

猜你喜欢

热点阅读