js继承

作者: silvacheng | 来源:发表于2017-12-22 09:34 被阅读0次

一:原型链继承
JavaScript的原型继承实现方式就是:

1.定义新的构造函数,并在内部用call()调用希望“继承”的构造函数,并绑定this;

2.借助中间函数F实现原型链继承,最好通过封装的inherits函数完成;

3.继续在新的构造函数的原型上定义新方法。

  function Student (props) {
      this.name = props.name || 'unnamed';
  }

  Student.prototype.hi = function () {
    alert(`hi ${this.name}~`);  
  }      
  
  function PrimaryStudent (props) {
    Student.call(this, props):
    this.grade = props.grade || 1
  }
  
  // 实现继承的函数inherits
  function inherits (Child, Parent) {
    var F = function () {};
    F.prototype = Parent.prototype;
    Child.prototype = new F();
    Child.prototype.constructor = Child;
  }
  // 实现原型继承链:
  inherits (PrimaryStudent, Student);

  // 绑定其他方法到PrimaryStudent原型:
  PrimaryStudent.prototype.getGrade = function () {
    return this.grade;
  }

  其实就是修改原型链为:
  new PrimaryStudent() ----> PrimaryStudent.prototype ----> Student.prototype ---->   Object.prototype ----> null

二: ES6 class继承
新的关键字class从ES6开始正式被引入到JavaScript中。class的目的就是让定义类更简单

 class Student {
    constructor (name) {
      this.name = name;
    }
    hi () {
      alert(`hi ${this.name}~`)
    }
  }
// 用class来定义对象的一个好处是继承方便,直接使用关键字extends

 class PrimaryStudent extends Student {
    constructor (name, grade) {
      super(name); // 使用super调用父类的构造函数
      this.grade = grade;
     }
    myGrade () {
      alert('I am at grade ' + this.grade);
    }
}

// 注意: 不是所有的主流浏览器都支持ES6的class 一定要现在就用上,就需要Babel工具把class代码转换为传统的prototype代码

相关文章

  • Js的继承

    js的继承 @(js)[继承, js, 前端] 组合继承是原性链继承和构造函数继承的合体,它汲取了二者各自的有点,...

  • JS继承

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

  • #js继承

    js继承的概念 js里常用的如下两种继承方式: 原型链继承(对象间的继承)类式继承(构造函数间的继承) 类式继承是...

  • js继承遇到的小问题

    这两天在看js继承方面,它不像OC那种传统的类继承。js继承方式还是挺多的。比如:原型继承、原型冒充、复制继承 原...

  • JS中继承的实现

    JS中继承的实现 #prototype (js原型(prototype)实现继承) 全局的Function对象没有...

  • js继承

    js继承js 继承-简书 原型链实现集继承 上面的代码实现原型链继承最重要的son.prototype=new f...

  • JavaScript 10

    js继承的概念 1.通过原型链方式实现继承(对象间的继承) 2.类式继承(构造函数间的继承) 由于js不像Java...

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

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

  • 2019-03-25 继承

    js中通过原型来实现继承 组合继承:原型继承+借用构造函数继承

  • 继承方式(6种)1.7

    JS作为面向对象的弱类型语言,继承也是其非常强大的特性之一。那么如何在JS中实现继承呢?让我们拭目以待。 JS继承...

网友评论

      本文标题:js继承

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