【发布时间】:2016-08-17 03:09:52
【问题描述】:
我从stackoverflow中读到了这段代码,说明了如何在javascript中实现“继承”
var Base=function(){this.a='abc'};
var Sub = function () {};
Sub.prototype = new Base(); // note: this pattern is deprecated!
//Because we used 'new', the [[prototype]] property of Sub.prototype
//is now set to the object value of Base.prototype.
//The modern way to do this is with Object.create(), which was added in ECMAScript 5:
Sub.prototype = Object.create(Base.prototype);
我想知道,如果
Sub.prototype = new Base();
已弃用,采用新方式
Object.create(Base.prototype);
介绍正在创建的对象的任何内部差异?有什么内部属性差异,行为差异,所以我应该使用新的方式,并尝试将旧代码转换为新代码?
谢谢。
【问题讨论】:
-
最大的不同是 Object.create 不会调用 Base 函数。它只是将该函数设置为原型并设置原型链。
标签: javascript object inheritance prototype