JS的继承模式有:
1.原型链继承
function Person(name) {
this.name = name
}
Person.prototype.showName = function() {
console.log(this.name)
}
let p = new Person('zyy')//'zyy'
//对象p自己没有showName函数,但它的原型上有所以它可以继承到这个方法。
2.构造函数继承
function Person(name,age) {
this.name = name
this.age = age
}
function Student() {
Person.call(this,name,age)
console.log(this.age,this.name)
}
let stu = new Student('zyy',24)
3.组合继承(原型链+构造函数)
function Person(name,age) {
this.name = name
this.age = age
}
function Student() {
Person.call(this,name,age) //实现构造函数继承
}
Student.prototype.showName = function() {
console.log(this.name,this.age)
}
let stu = new Student('zyy',24)
stu.showName() //实现原型链继承
4.ES6的extends关键字继承
class Person {
constructor(name) {
this.name = name
}
}
Person.prototype.showName = function () {
console.log(this.name)
}
Person.prototype.showAge = function () {
console.log(this.age)
}
class Student extends Person {
constructor(age) {
super() // 调用父类构造器
this.age = age
}
}
let stu = new Student('zyy',24)
stu.showName() //调用父类的方法 'zyy'
stu.showAge() //调用父类的方法 24
以上是我对JS常用继承模式的总结,欢迎各位童鞋的批评和意见!