JS-最容易理解的继承方式

232 阅读2分钟
继承方式核心关系
原型继承把父类公有作为子类公有继承公有属性
构造继承把父类私有作为子类私有继承私有属性
组合继承把父类公有作为子类公有,把父类私有作为子类私有原型继承+构造继承
寄生继承构造一个代理,让代理的 prototype 指向父类的 prototype在原型继承的基础上进行增强
ES6继承extends继承父类所有属性

原型继承

//定义父类
function Father(){
    //定义父类的私有属性
    this.name = '笨鸟';
    this.age = 24;
}

//定义父类的原型方法
Father.prototype.get = function(){
    console.log(this.name,this.age);
}

//定义中间商用来代理父类的原型对象
function Ann(){}
Ann.prototype = Father.prototype;
Child.prototype = new Ann();//将中间商的实例化对象,作为子类的原型对象
Chile.prototype.constructor = Child;//修复constructor指向

//定义子类继承父类
function Child(){}
var obj = new Child();
console.log(obj);

构造继承

//定义父类
function Father( name, age){
    //定义父类的私有属性
    this.name = name;
    this.age = age;
}

//定义父类的原型方法
Father.prototype.get = function(){
    console.log(this.name, this.age);
}

//定义子类继承父类
function Child( name, age){
    Father.call( this, name, age);
}

//当进行实例化操作时,构造函数中的this指向当前实例化对象
var obj = new Child('笨鸟',24);
console.log(obj);

组合继承

//定义父类
function Father(name,age){
    this.name = name;
    this.age = age;
}
Father.prototype.school = 'Good';

//继承公有属性和方法(原型继承)
function Ann();
Ann.protoype = Father.prototype;
Child.prototype = new Ann();
Child.prototype.constructor = Child;

//继承私有属性(构造继承)
function Child(name,age){
    Father.call(this,name,age);
}
var obj = new Child('笨鸟',24);
console.log(obj);

寄生继承

//定义父类
function Father(){
    //定义父类的私有属性
    this.name = '笨鸟';
    this.age = 24;
}

//定义父类的原型方法
Father.prototype.get = function(){
    console.log(this.name,this.age);
}

//定义中间商用来代理父类的原型对象
function Ann();
Ann.protoype = Father.prototype;
function Child(){}//定义子类继承父类
Child.prototype = new Ann();//将中间商的实例化对象,作为子类的原型对象
Child.prototype.constructor = Child;//修复constructor指向
Ann.prototype.school = 'Good';

var obj = new Child();
console.log(obj);

ES6继承

//定义父类
class Father {
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }
  get() {
    console.log("个人信息:" + this.name + this.age);
  }
}
//定义子类
class Child extends Father {
    //构造函数继承父类属性
    constructor(name, age) {
        super(name, age);
    }
}

let obj = new Child('笨鸟',25);
console.log(obj);