2019-06-18 JS 中继承的写法

  1. 使用 prototype 如何继承
       function Human(name){
           this.name = name
       }
       Human.prototype.run = function(){
           console.log("我叫"+this.name+",我在跑")
           return undefined
       }
       function Man(name){
           Human.call(this, name)
           this.gender = '男'
       }

       var f = function(){}
       f.prototype = Human.prototype
       Man.prototype = new f()

       Man.prototype.fight = function(){
           console.log('糊你熊脸')
       }
  1. 使用 class 语法糖如何继承

     ```
      class Human{
          constructor(name){
              this.name = name
          }
          run(){
              console.log("我叫"+this.name+",我在跑")
              return undefined
          }
      }
      class Man extends Human{
          constructor(name){
              super(name)
              this.gender = '男'
          }
          fight(){
              console.log('糊你熊脸')
          }
      }
    
3. 上面两个方法的区别

ES5中:

利用借用构造函数实现 实例属性和方法的继承 ;
利用原型链或者寄生式继承实现 共享的原型属性和方法的继承 。

ES6中:

利用class定义类,extends实现类的继承;
子类constructor里调用super()(父类构造函数)实现 实例属性和方法的继承;
子类原型继承父类原型,实现 原型对象上方法的继承。

你可能感兴趣的:(2019-06-18 JS 中继承的写法)