4 个回答

字面量继承自Object
Object.create继承自接受的参数

简单说下应用场景吧,
Object.create 目前知道的有两个地方:

  1. 实现继承,传入参数是现有对象,作为新创建的对象的__proto__值,实现继承,
  2. 创建一个干净的对象,Object.create(null),可以发现通过这种方式创建的对象没有__proto__值,也没有构造函数和原型链上一堆方法。最早是从vue源码里面看到了,有大量这类用法,

{}字面量,,方便初始化创建大量静态键值对,同时可以手动设置__proto__达到更Object.creat类似效果。

var o = {}
var b = Object.create(o)
b.__proto__ === o
const a = { a: 1 };
const b = Object.create(a);

[a, b].forEach(v => {
    v.b = "hello";
    console.log("--", v, v.a);
    console.log("KEYS: ", Reflect.ownKeys(v).join(","));
});

console.log(
    "prototype of a is ",
    Reflect.getPrototypeOf(a),
    ", is it Object.prototype? ",
    Reflect.getPrototypeOf(a) === Object.prototype
);

console.log(
    "prototype of b is ",
    Reflect.getPrototypeOf(b),
    ", is it a? ",
    Reflect.getPrototypeOf(b) === a);
-- { a: 1, b: 'hello' } 1
KEYS:  a,b
-- { b: 'hello' } 1
KEYS:  b
prototype of a is  [Object: null prototype] {} , is it Object.prototype?  true
prototype of b is  { a: 1, b: 'hello' } , is it a?  true
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题