Object.create(X.prototype) VS new X

这里面文章出处
https://juejin.im/post/5914fdce44d904006c44dfac

new Test():
  1. create new Object() obj
  2. set obj.__proto__ to Test.prototype;
  3. return Test.call(obj) || obj;
    // normally obj is returned but constructors in JS can return a value
Object.create( Test.prototype )
  1. create new Object() obj;
  2. set obj.__proto__ to Test.prototype
  3. return obj;

可以看到其实new和Object.create前两个步骤都是一样,区别在第三步,其实就是Object.create不会执行构造函数,我们来两段更直接的代码

var a = new A();
var b = Object.create(B.prototype)
function A() {
    console.log('a')
}
function B() {
    console.log('b')
}
// 我们可以看到只输出了a,但是b并没有输出
var a = new A();
var b = Object.create(B.prototype)
function A() {
  return {}
}
function B() {
  return {}
}
console.log(a)
console.log(b)
// 可以看到a就是{}
// b是一个对象,它的__proto__指向B.prototype

这样应该就很清晰了,Object.create()特殊还在于它的第二个参数,就像Object.defineProperties()可以定义新的属性或修改现有属性

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值