原型链和构造函数组合继承
function Animal(color){ //父类
this.color= color
this.type = ["cat","dog"]
console.log("Animal Class") //看下这个构造函数执行了几次
}
Animal.prototype.getColor = function(){
return this.color
}
function Dog(name){ //子类
Animal.apply(this,[...arguments]) // 构造函数继承方式//继承构造函数内属性(每个子类实例的属性不同)
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") //看下这个构造函数执行了几次
}
Animal.prototype.getColor = function(){
return this.color
}
function Dog(name){ //子类
Animal.apply(this,[...arguments]) // 构造函数继承方式//继承构造函数内属性(每个子类实例的属性不同)
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) // 调用父类的constructor(color)
// 相当于ES5中Animal.apply(this,[...arguments])
// 另一个需要注意的地方是,在子类的构造函数中,只有调用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)