JS 加油包之继承

152 阅读1分钟

如何实现继承?这里记录两种方法,分别使用和避开使用了class实现继承

  1. 避开使用 class
function Animal(color){ 
    // 声明一个函数Animal
    this.color = color
}
Animal.prototype.move = function(){} 
// 给Animal添加move属性
function Dog(color, name){ 
    // 声明一个函数Dog,有参数color和name
    Animal.call(this, color) 
    // Dog继承Animal的color属性
    this.name = name 
    // Dog的孩子继承Dog的name属性
}

function temp(){} 
// 声明一个工具人函数temp
temp.prototype = Animal.prototype 
// temp继承Animal
Dog.prototype = new temp() 
// Dog的原型是temp的构造函数,继承temp
//  Dog的prototype对象指向temp实例
Dog.prototype.constructor = Dog
//  任何一个prototype对象都有一个constructor属性,指向他的构造函数。如果没有上面这一行,那么Dog.prototype.constructor是指向Dog的,写上这一行以后,Dog.prototype.constructor指向Animal???
Dog.prototype.say = function(){console.log('hi')}
var dog = new Dog('黄色','阿黄')
  1. 使用 class
class Animal{
    constructor(color){
        this.color = color
    }
    move(){}
}
class Dog extends Animal{
    constructor(color, name){
        super(color) 
        // A constructor can use the super keyword to call the constructor of the super class
        //  一个 构造函数可以使用 super 关键字来调用一个父类的构造函数
        this.name = name
    }
    say(){}
}

Reference List | 参考资料
阮一峰:非构造函数的继承
阮一峰:构造函数的继承
MDN: Classes