继承之es5对比es6
es5 写法:
function Person(name){ this.name = name; } Person.prototype.sayName = function() { alert(this.name); } function VipPerson(name,level){ Person.call(this,name); this.level = level; } // 组合继承(缺点是prototype这一层多了一些无用的undefined属性) // VipPerson.prototype = new Person(); // VipPerson.prototype.constructor = VipPerson; //重写construtor // 寄生组合继承 VipPerson.prototype = Object.create(Person.prototype, { constructor: { //重写construtor value: VipPerson, enumerable: false, configurable: true, writable: true } }) var vipPerson = new VipPerson('amie',3);
es6的写法:
相比于es5,es6的写法简化了很多,extends、super就可以完成上面寄生组合继承的效果
super
,可以看成 Person.call(this, name)
。
class Person{ constructor(name){ this.name = name; } sayName(){ alert(this.name); } } class VipPerson extends Person{ constructor(name,level){ super(name); this.level = level; } } var person2 = new VipPerson('rick',3)