JS常用继承方式

原型链和构造函数组合继承

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)
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容