原型继承(实现Person和Student对象)

225 阅读1分钟

题目

按照如下要求实现Person和Student对象

  • 1:Student继承Person
  • 2:Person包含一个实例变量name,包含一个方法printName
  • 3:Student包含一个实例变量score,包含一个实例方法printScore
  • 4:所有Person和Student对象之间共享一个方法
// ES6写法
class Person{
    constructor(name){
       this.name
    }
    printName(){}
    commonMethods(){
       console.log('共享的方法')
    }
}
class Student extends Person{
    constructor(name,score){
      super(name)
      this.score = score
    }
    printScore(){}
}

原生写法

// Pserson对象
function Person(name){
    this.name
    this.printName = function(){}
}
// 共享的方法
Person.prototype.commonMethods = function(){
    console.log('共享方法')
}
function Student(name,score){
    this.name = name
    this.score = score
    this.printScore = function(){}
}
Student.prototype = new Person()