class extends实现继承

/** ES5 通过修改原型链实现继承 */
(function() {
  // 1. 创建两个构造函数
  function Animal(name, age) {
    this.name = name;
    this.age = age;
  }
  Animal.prototype.eat = function (type) {
    return `${type} food`;
  }

  function Human(name, age, work) {
    /**
     * apply: 调用一个对象的一个方法,用另一个对象替换当前对象。
     *		例如:B.apply(A, arguments);即A对象调用B对象的方法。
     * call:调用一个对象的一个方法,用另一个对象替换当前对象。
     * 		例如:B.call(A, args1,args2);即A对象调用B对象的方法。
     * 
     * 两者最大的取别就是: apply 传入一个 arguments, call 是一个一个的传参;
     */

     /**
      * bind & call: 两者的使用方法一致,
      *  取别: call 是立即执行,
      *        bind() 方法创建一个新的函数,在 bind() 被调用时,
      * 					这个新函数的 this 被指定为 bind() 的第一个参数,
      * 					而其余参数将作为新函数的参数,供调用时使用。
      */
    
    // 2. 在 子构造函数中 调用 父构造函数
    Animal.call(this, ...[name, age]);
    // Animal.apply(this, [name, age]);
    this.work = work;
  }

  /**
   * 3. 实现继承,将子类的原型对象 prototype 指向 父类 原型对象,
   */

  // 让 Human 这个构造函数的 原型对象 指向 animal 的实例,
  // 这样的,实例的 __proto__ 也会被 human 继承;
  // Human.prototype = new Animal()

  Human.prototype = Object.create(Animal.prototype, {
    constructor: {
      value: Human,
    }
  })

  Human.prototype.constructor = Human

  const codePerson = new Human('阿伟', 27, 'coder')
  // console.log(codePerson, codePerson.eat('cooked'));
  
})();

/** class 继承 */

(function() {
  class Animal {
    constructor(name, type) {
      this.name = name
      this.type = type
    }
    getName() {
      return this.name
    }
    static getType() {
      return 'all animal'
    }
  }

  /**
   * 1. class 通过 extends 关键字 实现继承
   */
  class Human extends Animal {
    // 
    constructor (name, type, work) {
      /**
       * 2. 子类必须在 constructor 方法中调用 super 方法,此 super 方法表示 父类的 constructor
       * 
       * 此时 super 相当于 Animal.call(this, ...[name, age]);
       * 
       * 注意: 
       *    在子类的构造函数中,只有调用super之后, 才可以使用this关键字,否则会报错;
       *    且super必须在 constructor 的第一行调用
       */
      super(name, type)
      this.work = work
    }

  }
  const codePerson = new Human('阿伟', '27', 'coder')
  console.log(codePerson.getName()) // 阿伟 

  // 3. Human 会继承 父类的静态方法
  console.log(Human.getType()) // all animal

  // 4. 可以通过 getprototypeOf() 判断 一个类 是否继承自 另一个类;
  console.log(Object.getPrototypeOf(Human) === Animal) // true
})();

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值