Javascript之原型继承和class类继承

一、原型继承

先创建一个构造函数Person,添加属性原型添加方法

function Person(name,age) {
  this.name = name
  this.age = age
}

Person.prototype.getName = function () {
  return this.name
}

再创建一个构造函数Student 并且调用Person构造函数

function Student(name,age,className) {
  Person.call(this,name,age)
  this.className = className
}

这里要先继承Person的实例,再给Student原型添加方法

Student.prototype = new Person()

Student.prototype.getClassName = function () {
  return this.className
}

最后实例化,完美继承了Person的属性/原型,同时拥有自己的原型方法

let student = new Student('小二',13,'一年级')

console.log(student.getName()) // 小二
console.log(student.getClassName()) // 一年级

二、class

创建Person 构造函数 ,添加赋值属性,原型添加方法

class Person {
  constructor(name,age){
    this.name = name
    this.age = age
  }
  getName(){
    return this.name
  }
}

创建Student构造函数,并且继承Person (super构造函数)

class Student extends Person{
  constructor(name,age,className){
    super(name,age)
    this.className = className
  }
  getClassName(){
    return this.className
  }
}

完美继承Person属性 原型方法

let student = new Student('小二',13,'一年级')

console.log(student.getName()) // 小二
console.log(student.getClassName()) // 一年级
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章