美文网首页
Object.create()

Object.create()

作者: Allan要做活神仙 | 来源:发表于2019-03-25 15:31 被阅读0次

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的值。

相关文章

网友评论

      本文标题:Object.create()

      本文链接:https://www.haomeiwen.com/subject/vxfbvqtx.html