一、原型繼承
先創建一個構造函數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()) // 一年級