1、原型继承
把父类的实例作为子类的原型
缺点:子类的实例共享了父类构造函数的而引用属性 不能传参
优点:可传参,不共享父类的而引用属性
var person = {
friends: ["a","b","c","d"],
}
var p1 = Object.create(person)
p1.friends.push("aaa")
console.log(p1)
console.log(person)
2、组合继承
在子函数中运行函数,但是要利用call把this改变一下
再把子函数的prototype里面的new Father的原型中的方法也得到继承,最后改变
缺点:调用了两次父类的构造函数,造成了不必要的消耗,父类方法可以复用
优点:可传参,不共享父类的而引用属性
function Father(name) {
this.name = name
this.body = ["篮球","足球","乒乓球"]
}
Father.prototype.getName = function() {
console.log(this.name)
}
function Son(name,age) {
Father.call(this,name)
this.age = age
}
Son.prototype = new Father()
Son.prototype.constructor = Son
console.log(Son)
var s = new Son("ming",20)
console.log(s)
3、寄生组合继承
function Father(name) {
this.name = name
this.body = ["篮球","足球","乒乓球"]
}
Father.prototype.getName = function() {
console.log(this.name)
}
function Son(name,age) {
Father.call(this,name)
this.age = age
}
Son.prototype = Object.create(Father.prototype)
Son.prototype.constructor = Son
var s2 = new Son("ming",18)
console.log(s2)
4、es6 extend继承(寄生组合继承的语法糖)
子类只要继承父类,可以不写constructor,一旦写了,则在construc中第一句话
必需是super
class Son3 extends Father {
constructor(y) {
super(200) //super(200) => {Father.call(this,200)}
this.y = y
}
}