美文网首页程序员
js继承的多种实现方式

js继承的多种实现方式

作者: 慕时_木雨凡 | 来源:发表于2019-03-22 14:11 被阅读0次

Father作为父类,Child作为子类,继承的目标是让子类可以访问到父类的属性和方法

function Father () {
  this.name = name
  this.age = age
  this.run = function () {
    console.log('加油')
  }
}
function Child (name, age) {}
let tom = new Child()

1.原型链继承

实现简单、方便理解。就是将父类挂载在子类的prototype上。

function Father () {
  this.run = function () {
    console.log('加油')
  }
}
function Child (name, age) {
  this.name = name
  this.age = age
}
Child.prototype = new Father()
let tom = new Child('tom', 6)
tom.run()  // 加油
console.log(tom.name)  // tom
console.log(tom.age)     // 6

缺点:无法实现多继承

2.构造继承(利用call、apply的特性实现)

利用call或者apply改变子类的this指向。从而实现在子类中调用父类的方法

function Father (name, age) {
  this.name = name
  this.age = age
  this.run = function () {
    console.log('加油')
  }
}
function Child (name, age) {
  Father.call(this, ...arguments)
}
Child.prototype = new Father()
let tom = new Child()
tom.run()  // 加油 

缺点:只能继承父类的实例,不能继承父类的原型

3.组合继承(原型链继承+构造继承)

结合原型链继承和构造继承的优点(推荐使用)

function Father (name, age) {
  this.name = name
  this.age = age
  this.run = function () {
    console.log('加油')
  }
}
function Child (name, age) {
  Father.apply(this, arguments)
}
Child.prototype = new Father()
let tom = new Child('tom', 19)
tom.run()  // 加油
console.log(tom.name)
console.log(tom.age)

4.原型继承或者叫实例继承

对子类进行函数封装且返回父类,new Child() --> 相当于 new Father()。从而实现继承

function Father (name) {
  this.name = name
  this.run = function () {
    console.log('加油')
  }
}
function Child (name) {
  let instance = new Father(...arguments);
  return instance;
}

let tom = new Child('tom')
tom.run()  // 加油
console.log(tom.name)

5.拷贝继承

利用for in 循环将父类的属性进行循环往子类的prototype中添加。

function Father () {
  this.run = function () {
    console.log('加油')
  }
}

function Child(name){
  let father = new Father();
  for(let p in father){
    Child.prototype[p] = father[p];
  }
  Child.prototype.name = name;
}
let tom = new Child('tom')
tom.run()
console.log(tom.name)

缺点:执行效率比较低

相关文章

  • js继承的多种实现方式

    Father作为父类,Child作为子类,继承的目标是让子类可以访问到父类的属性和方法 1.原型链继承 实现简单、...

  • 继承

    研究学习了js内部的继承方式,以及多种方式的优点和缺点 目前项目中的 以前项目中的 js中继承有多种方式 原型继承...

  • js继承的多种方式

    《JavaScript高级程序设计》提到了6中继承方式:1.原型链继承2.借用构造函数(经典继承)3.组合继承4....

  • JS继承的多种方式

    1:原型链继承 推荐指数:?? 特点: ❀ 将父类的实例作为子类的原型继承❀ 这样子类实例化出来的对象即子类的实例...

  • 扣丁学堂JavaScript实现面向对象继承的五种方式

    今天扣丁学堂老师给大家主要介绍了JS实现面向对象继承方式的详解,首先js是门灵活的语言,实现一种功能往往有多种做法...

  • JS继承的实现的几种方式

    前言 JS作为面向对象的弱类型语言,继承也是非常强大的特性之一,那么如何在JS实现继承呢? JS继承的实现方式 既...

  • js中的继承-原型与原型链

    面向对象的语言支持两种继承方式,接口继承和实现继承js无法实现接口继承,只支持实现继承,主要通过原型链来实现。具体...

  • JS继承

    JS中的继承 许多OO语言都支持两种继承方式:接口继承和实现继承; 因为JS中没有类和接口的概念 , 所以JS不支...

  • js基础之实现继承的几种方式

    js 实现继承的方式有: 原型链继承; 构造函数继承; 组合继承(原型链继承 + 构造函数继承)(最常用);(原型...

  • JS实现继承方式

    js中的继承: Object是所有对象的父级/父类型/超类型,js中所有的对象都直接或间接的继承自Object. ...

网友评论

    本文标题:js继承的多种实现方式

    本文链接:https://www.haomeiwen.com/subject/wrllvqtx.html