浅谈Object.create

在网上发现了Object.create的用法,感觉很是奇怪,所以学习记录下

1 var o = Object.create(null);
2 console.log(o); // {}
3 o.name = 'jian';
4 var o2 = Object.create(o);
5 console.log(o2); // {}
6 console.log(o2.name); // 'jian', 

百度了一下原理:

1 Object.create =  function (o) {
2     var F = function () {};
3     F.prototype = o;
4     return new F();
5 };

再看一段代码:

1 var Base = function () {2 }
3 Base.prototype.a = 3;
4 var o1 = new Base();
5 var o2 = Object.create(Base);
6 console.log(o1.a);//3
7 console.log(o2.a);//undefined
8 o2.__proto__.prototype.a//3

为什么呢:因为o2的原型链中并没有a这个属性但是根据之前代码Object.create的原理来看return new F();

那么假设这个o2=new F();因此可以推出o2.__proto__ = F.prototype=Base(此原理请参见之前文章面向对上中的图二),而Base.prototype.a = 3;

因此o2.__proto__.prototype.a=3

posted @ 2018-02-19 17:28  Ones(小万)  阅读(223)  评论(0编辑  收藏  举报