JS继承之extends

JavaScript017

JS继承之extends,第1张

ES6中有关 class 的继承方式,引入了 extends 关键字。

但其本质仍然是 构造函数 + 原型链的 组合式继承。

上述 B 类 (class)通过 extends 关键字,继承了 A 类 的所有属性和方法。 A 类 中的所有方法默认是添加到 B 的原型上,所以 extends 继承的实质仍然是原型链。

super 这个关键字,既可以当作函数使用,也可以当作对象使用。当作函数使用时 super 代表父类的构造函数,并在子类中执行 Parent.apply(this) ,从而将父类实例对象的属性和方法,添加到子类的 this 上面。

特别注意

因为类必须通过 new 关键字调用,所以在类的构造函数中 new.target 的值永远不会是 undefined 。

继承的方式一共有三种:

一、原型继承

通过prototype 来实现继承。

function Person(name,age) { this.name=namethis.age=age

}

Person.prototype.sayHello=function(){

alert (''使用原型得到Name:'' + this.name)

}var per = new Person("马小倩",21)

per.sayHello()//输出:使用原型得到Name:马小倩

function Student(){}

Student.prototype=new Person("洪如彤",21) //实现原型继承

var stu = new Student()

Student.prototype.grade=5

Student.prototype.intr=function(){

alert(this.grade)

}

stu.sayHello()//输出:使用原型得到Name:洪如彤

stu.intr()//输出:5

二、构造函数实现继承

function Person(name,age) { this.name=namethis.age=age

}

Person.prototype.sayHello=function(){

alert (''使用原型得到Name:'' + this.name)

}var per = new Person("马小倩",21)

per.sayHello()//输出:使用原型得到Name:马小倩

三、 通过call、apply 实现继承