js构造函数+原型链 实现继承

ES5形式

  function fun() {
    this.name = 'fun',
    this.arr = [1,2,3]
  }

  fun.prototype.myLog = function() {
    console.log(this.arr);
  }

  function cFun () {
    fun.call(this) //call调用父函数 继承父函数的属性
    this.type = 'child'
  }

  cFun.prototype = fun.prototype // 构造函数的原型对象指向要继承的父函数的原型对象
  cFun.prototype.constructor = cFun

  var c1 = new cFun()
  console.log(c1);
  c1.myLog()
  console.log(c1 instanceof cFun); // true
  console.log(f1 instanceof cFun); // true

执行结果如图:


image.png

缺点:因为父函数和子函数都是同一个对象,导致父函数和子函数的实例对象,在执行instanceof时,都为true 无法区分。
用Object.creacte(fun.prototype)创建中间对象的形式可以解决这个问题

ES6形式

  class Teacher {
    constructor(name) {
        this.name = name
        this.age = 30
    }
    sayHi() {
        console.log(`hello everyone,我叫${this.name}`);
    }
  }

  class Student extends Teacher {
    constructor(name) {
        super(name)
        this.name = name
    }
    sayHello() {
        console.log(`大家好,我叫${this.name}`);
    }
  }

  const stu1 = new Student('张三')
  console.log(stu1);
  stu1.sayHello()
  stu1.sayHi()

结果如下:


image.png
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容