js的原型与继承,prototype的使用

使用使用构造函数结合原型定义一个学生对象类,学生信息包括:姓名,学号,年龄,班级信息等,在原型上定义几个方法。生成一个学生对象并调用几个方法。

  // 父类
  function StudentInfo(params) {
    this.name = '小明'
    this.sex = '男'
    this.age = '18'
    this.grade = '一班'
  }

  // 原型上添加方法
  StudentInfo.prototype.call = function () {
    console.log('我的名字叫' + this.name)
  }

  //构造函数
  function Student(params) {
    //构造方法继承
    StudentInfo.apply(this, params)
  }

  // 原型链继承
  Student.prototype = new StudentInfo()

  // 创造两个实例
  const student1 = new Student()
  const student2 = new Student()

  // 实例自己的数据
  student1.name = '小红'

  student1.call()//我的名字叫小红
  student2.call()//我的名字叫小明

只看代码不加深理解可不好,我对js的继承做了总结,这里的问题是涉及其中的组合继承,欢迎有空来我的博客进行学习
本文链接: