原型鏈和構造函數(shù)組合繼承
function Animal(color){ //父類
this.color= color
this.type = ["cat","dog"]
console.log("Animal Class") //看下這個構造函數(shù)執(zhí)行了幾次
}
Animal.prototype.getColor = function(){
return this.color
}
function Dog(name){ //子類
Animal.apply(this,[...arguments]) // 構造函數(shù)繼承方式//繼承構造函數(shù)內(nèi)屬性(每個子類實例的屬性不同)
this.name = name
}
Dog.prototype = new Animal() //原型繼承方式 //繼承公用方法(每個子類實例的方法相同)
var dog1 = new Dog("xiaoming","blue")
var dog2 = new Dog("xiaohuang","black")
dog1.type.push("fakedog")
console.log(dog1)
console.log(dog2)
寄生組合式繼承
function Animal(color){ //父類
this.color= color
this.type = ["cat","dog"]
console.log("Animal Class") //看下這個構造函數(shù)執(zhí)行了幾次
}
Animal.prototype.getColor = function(){
return this.color
}
function Dog(name){ //子類
Animal.apply(this,[...arguments]) // 構造函數(shù)繼承方式//繼承構造函數(shù)內(nèi)屬性(每個子類實例的屬性不同)
this.name = name
}
Dog.prototype = Object.create(Animal.prototype)
Dog.prototype.constructor = Dog
var dog1 = new Dog("xiaoming","blue")
var dog2 = new Dog("xiaohuang","black")
dog1.type.push("fakedog")
console.log(dog1)
console.log(dog2)
ES6的class繼承
// 定義父類
class Animal{
constructor(color){
this.color = color
this.type = ["cat","dog"]
console.log("Animal Class")
}
getColor(){
return this.color
}
}
// 定義子類
class Dog extends Animal{
constructor(name,color){
super(color) // 調(diào)用父類的constructor(color)
// 相當于ES5中Animal.apply(this,[...arguments])
// 另一個需要注意的地方是,在子類的構造函數(shù)中磨淌,只有調(diào)用super之后疲憋,才可以使用this關鍵字,否則會報錯梁只。
this.name = name
}
getName(){
return this.name
}
}
var dog1 = new Dog("xiaocai","yellow")
var dog2 = new Dog("xiaoyun","pink")
dog1.type.push("realdog")
console.log(dog1)
console.log(dog2)