// 在ES5中,通常使用构造函数方法去实现类与继承
1 // 创建父类 2 function Father(name, age){ 3 this.name = name; 4 this.age = age; 5 } 6 Father.prototype.show = function(){ 7 console.log(this.name); 8 console.log(this.age); 9 } 10 11 const obj = new Father('李大师', 30); 12 obj.show(); // 输出 李大师 30 13 14 // 创建子类,然后让子类继承父类 15 function Child(name,age,sex){ 16 //继承第一句:让子类实例化的对象具备父类的所有属性 17 Father.apply(this,arguments); 18 this.sex = sex; 19 } 20 //继承第二句:让子类实例化对象具备父类的所有原型方法 21 Child.prototype = Object.create(Father.prototype); 22 23 //继承第三句:找回丢失的构造函数 24 Child.prototype.constructor = Child; 25 26 Child.prototype.run = function(){ 27 console.log(this.sex) 28 } 29 30 const son = new Child('123', 10, 'boy'); 31 son.show(); // 输出 123 10 32 son.run(); // 输出boy
// ES6中,类的实现和继承非常方便
class SuperClass{ //实例化类时默认会执行构造函数 constructor(name,age){ //初始化对象的语句 this.name=name; this.age=age; } //原型方法 show(){ console.log(this.name); console.log(this.age); } } const sup = new SuperClass('super', 20); sup.show(); // 输出 super 20 class SonClass extends SuperClass{ constructor(name, age, sex){ super(name,age); // name 和 age属性可以继承父类 this.sex = sex; // sex 属性 子类自己定义 } run(){ console.log(this.sex); } } const sonclass = new SonClass('abc', 15, 'girl'); sonclass.show(); // 输出 abc 15 sonclass.run(); // 输出 girl