方法一:使用class
class Person{constructor(name, age){this.name = namethis.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 = schoolthis.grade = grade}study(){console.log("好好学习,天天向上")}}const lilei = new Student('李雷', 12, '实验小学', 5)lilei.sayHi()lilei.study()
方法二: 使用原型链
function Person(name, age){this.name = namethis.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 = schoolthis.grade = gradePerson.call(this, name, age)}Student.prototype.__proto__ = Person.prototypeStudent.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.prototypeStudent.prototype = new f()
