实现继承

  • 不用 class

    1. function Animal(color){
    2. this.color = color
    3. }
    4. Animal.prototype.move = function(){} // 动物可以动
    5. function Dog(color, name){
    6. Animal.call(this, color) // 或者 Animal.apply(this, arguments)
    7. this.name = name
    8. }
    9. // 下面三行实现 Dog.prototype.__proto__ = Animal.prototype
    10. function temp(){}
    11. temp.prototype = Animal.prototype
    12. Dog.prototype = new temp()
    13. Dog.prototype.constuctor = Dog // 这行看不懂...
    14. Dog.prototype.say = function(){ console.log('汪')}
    15. var dog = new Dog('黄色','阿黄')
  • 用 class 就比较简单

    1. class Animal{
    2. constructor(color){
    3. this.color = color
    4. }
    5. move(){}
    6. }
    7. class Dog extends Animal{
    8. constructor(color, name){
    9. super(color)
    10. this.name = name
    11. }
    12. say(){}
    13. }