JS继承

构造函数继承

只会继承构造函数本身的属性方法,不会继承原型中的。

var Parent=function(){
  this.name='名字',
  this.func=function(){
    alert('方法')
  }
}
Parent.prototype={
  getName:function(){
    alert(this.name)
  }
}
var Child=function(){
  Parent.call(this)//call和apply都可以
}
// 相当于吧父类当成一个函数在子类中运行,并且改变this为子类实例,这样就相当于拷贝了 父类中构造函数中的属性和方法,实现构造函数继承,但是无法继承原型中的方法和属性
var child=new Child()
console.log(child)

原型链继承

原型和实例都可以继承,就是子类和父类共享一个原型

var Parent=function(){
  this.name='名字',
  this.age=25,
  this.func=function(){
    alert('方法')
  }
}
Parent.prototype={
  getName:function(){
    alert(this.name)
  }
}
var Child=function(){
  this.childName='子名字'
}
Child.prototype=new Parent()
var child=new Child()
console.log(child)
// 利用js原型链的特点将子类的原型等于父类的实例,那么子类在原型链访问过程中就可以访 问到父类的属性和方法,问题,多个实例共享一个原型

组合继承 借用构造函数 + 原型式继承

var Parent=function(){
  this.name='名字',
  this.age=25,
  this.func=function(){
    alert('方法')
  }
}
Parent.prototype={
  getName:function(){
    alert(this.name)
  }
}
var Child=function(){
  Parent.call(this)
}
Child.prototype=Parent.prototype
var child=new Child()
console.log(child)

class继承

class Parent {
  constructor(name){
    this.name="父类名字"
  }
  parentFunc(){
    alert(`${this.name}-parentFunc`)
  }
}
//使⽤extends即可实现继承,更加符合经典⾯向对象语⾔的写法
class Child extends Parent {
  constructor(name){
    super(name)//⼦类的constructor⼀定要执⾏super(),以调⽤⽗类的constructor
    this.name=name
    this.age=24
  }
  childFunc(){
    alert(`${this.name}-childFunc`)
  }
}
const child=new Child("名字")
console.log(child)
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 一、原型链 学过java的同学应该都知道,继承是java的重要特点之一,许多面向对象的语言都支持两种继承方式:接口...
    grain先森阅读 5,249评论 0 39
  • 原文链接 js的继承有6种方式,大致总结一下它们各自的优缺点,以及它们之间的关系。 1.原型链 js的继承机制不同...
    空_城__阅读 4,153评论 0 11
  • 继承的概念:子类可以使用父类共享的属性和方法,避免重复代码提高代码复用性。 原型链:子类可以共享父类的实例对象和实...
    浅秋_6672阅读 3,089评论 0 0
  • JS 实现继承的方法有:1.原型链继承2.构造函数继承3.组合继承(原型链继承 + 构造函数继承)4.原型式继承(...
    yun_154192阅读 4,099评论 0 0
  • 继承6种套餐 参照红皮书,JS继承一共6种 1.原型链继承 核心思想:子类的原型指向父类的一个实例 Son.pro...
    灯不梨喵阅读 8,375评论 1 2

友情链接更多精彩内容