方法一:使用class
class Person{
constructor(name, age){
this.name = name
this.age = age
}
sayHi(){
console.log(`hi, my name is ${this.name}, I'm ${this.age} year's old.`)
}
}
class Student extends Person {
constructor(name, age, school, grade) {
super(name, age)
this.school = school
this.grade = grade
}
study(){
console.log("好好学习,天天向上")
}
}
const lilei = new Student('李雷', 12, '实验小学', 5)
lilei.sayHi()
lilei.study()
方法二: 使用原型链
function Person(name, age){
this.name = name
this.age = age
}
Person.prototype.sayHi = function(){
console.log(`hi, my name is ${this.name}, I'm ${this.age} year's old.`)
}
function Student(name, age, school, grade){
this.school = school
this.grade = grade
Person.call(this, name, age)
}
Student.prototype.__proto__ = Person.prototype
Student.prototype.study = function(){
console.log("好好学习,天天向上")
}
const lilei = new Student('李雷', 12, '实验小学', 5)
lilei.sayHi()
lilei.study()
如果禁止使用Student.prototype.__proto__ = Person.prototype
,则应使用下面的代码代替
const f = function(){}
f.prototype = Person.prototype
Student.prototype = new f()