JS中new和Object.create()区别

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)的空对象是没有任何属性的。

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值