继承

继承是指一个对象直接使用另一对象的属性和方法

  • 得到一个类的属性
  • 得到一个类的方法

一、原型链实现继承

1、定义一个类
function Person(name,sex) {
    this.name=name;
    this.sex=sex;
}
Person.prototype.sayName = function(){
    console.log(this.name)
}
2、获取属性

对象属性的获取是通过构造函数的执行,在一个类中执行另一个类的构造函数,就可以把属性赋值到自己内部,但需要把环境改成自己的作用域内

function Male(name,age,sex){
    Person.call(this,name,age);
    this.sex=sex;
}
3、获取方法

类的方法一般定义在prototype里面

需要注意的几点:
  • 创建新的ptorotype,而不是直接把Person.proto赋值,因为引用关系,会导致修改子类的proto也修改了父类的prototype

  • 对子类添加方法,必须在修改其prototype之后,在之前会被覆盖

  • 此刻子类的constructor属性指向不对,需重新指定

关于手动指定对象的原型的几种方法:

  • object.proto={...}
Man.prototype.__proto__ = Person.prototype//不兼容低版本IE
  • 借用new
//原型继承
function Person(name, age){
  this.name = name
  this.age = age
}
Person.prototype.sayName = function(){
    console.log(this.name)
}
//让Man 继承Person
//1、继承属性:让Person在Man里面执行一遍
function Man (name, age, sex) {
  Person.call(this, name, age)
  this.sex = sex
}
//2、方法继承
var xxx = function (){}
xxx.prototype = Person.prototype
Man.prototype = new xxx()
//3、修正constructor
Man.prototype.constructor = Man
var yyy = new Man()
console.dir(yyy)
  • 使用Object.create()
//1、继承属性:让Person在Man里面执行一遍
function Man (name, age, sex) {
  Person.call(this, name, age)
  this.sex = sex
}
//2、方法继承
inherit(Person, Man)
function inherit(superType, subType) {
  var _prototype = Object.create(superType.prototype)
  _prototype.constructor = subType
  subType.prototype = _prototype
}
//3、在继承函数之后写自己的方法,不然会被覆盖
Man.prototype.saySex = function() {
  console.log(this.sex)
}
var yyy = new Man()
console.dir(yyy)

二、class继承

class可以通过extends关键字实现继承,比es5的通过修改原型链实现继承,要清晰和方便。

es5的继承,实质是先创造子类的实例对象this,然后再将父类的方法添加到this上面。

es6的继承机制完全不同,实质是先创造父类的实例对象this(所以必须先调用super),然后再用子类的构造函数修改this。

class Point {
  constructor(x,y){
    this.x=x;
    this.y=y;
  }
}

class ColorPoint extends Point {
  constructor(x,y,color) {
    super(x,y);//调用父类的constructor(x, y)
    this.color=color
  }
}
super
  • super作为函数调用时,代表父类的构造函数。es6要求,子类的构造函数必须执行一次super函数。
  • 此时,super虽然代表了父类的构造函数,但返回的子类的实例
  • super作为函数时,只能用在子类的构造函数中
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容