Object.create()

2019-03-25  本文已影响0人  Allan要做活神仙

2019-03-25于公司:

var a = {a1: 1};
var b = Object.create(a);

// 此时这个值不是吧b自身的,是它通过原型链`proto`来访问到b的值
b.a1; // 1

new Object()通过构造函数来创建对象, 添加的属性是在自身实例下。
Object.create() es6 创建对象的另一种方式,可以理解为 继承 一个对象, 添加的属性是在原型下。

// new Object() 方式创建
var a = {  rep : 'apple' }
var b = new Object(a)
console.log(b) // {rep: "apple"}
console.log(b.__proto__) // {}
console.log(b.rep) // {rep: "apple"}

// Object.create() 方式创建
var a = { rep: 'apple' }
var b = Object.create(a)
console.log(b)  // {}
console.log(b.__proto__) // {rep: "apple"}
console.log(b.rep) // {rep: "apple"}

Object.create()方法创建的对象时,属性是在原型下面的,也可以直接访问 b.rep // {rep: "apple"},
此时这个值不是吧b自身的,是它通过原型链proto来访问到b的值。

上一篇 下一篇

猜你喜欢

热点阅读