new操作符
首先我们来看new操作符:
function Animal(){}
var animal = new Animal();
如果你熟悉原型链的话(原型链分享),就会知道new操作符会在执行的时候将Animal.prototype赋值给animal.[[Prototype]]。
Object.create
我们先看下Object.create的语法:
Object.create(proto, [ propertiesObject ])
其中:
- proto是原型对象
- propertiesObject是属性的配置
function Animal(name){
this.name = name;
}
var animal = new Animal("test");
var createAnimal1 = Object.create(Animal.prototype);
var createAnimal2 = Object.create(animal);
var createAnimal3 = Object.create(null);
console.log(createAnimal1.name) // 输出为 undefined
console.log(createAnimal2.name) //输出为 test
console.log(createAnimal3) // 输出为 {}
也就是说,你可以任意指定对象的原型对象。
总结:
- new操作符会将那样构造函数的prototype指定的原型对象赋值给新对象的[[Prototype]]
- Object.create将参数proto指定的原型对象赋值给新对象的[[Prototype]]。
如果参数为null的话,Object.create则会创建空对象。
特别需要指出的是Object.create(null)和new Object()的区别:两者都是创建空对象,但是new创建出的空对象会绑定Object的prototype原型对象,但是Object.create(null)的空对象是没有任何属性的。