一、不同
function Super(){}
function Sub(){}
Sub.prototype = new Super()
Sub.prototype.constructor = Sub; // 为什么?为了 console.log(Sub.prototype.constructor)//[Function: Sub] ?
const subInstance = new Sub()
// es5 一个继承链
console.log(Sub.prototype.constructor)//[Function: Sub]
console.log(Super.prototype.constructor)//[Function: Super]
console.log( subInstance instanceof Sub) // true
console.log( subInstance instanceof Super) // true
class Point {
}
class ColorPoint extends Point {
constructor() { super() }
}
const cpInstance = new ColorPoint()
// ES6 两条继承链
console.log(ColorPoint.__proto__ === Point) // true
console.log(ColorPoint.prototype.__proto__ === Point.prototype) // true
console.log( cpInstance instanceof ColorPoint) // true
console.log( cpInstance instanceof Point) // true
二、注意
super 的使用
第一种情况,super作为函数调用时,代表父类的构造函数。ES6 要求,子类的构造函数必须执行一次super函数。
classA{}
classB extends A{
constructor(){super();}
}
super虽然代表了父类A的构造函数,但是返回的是子类B的实例,即super内部的this指的是B,因此super()在这里相当于A.prototype.constructor.call(this)。
第二种情况,super作为对象时,在普通方法中,指向父类的原型对象;在静态方法中,指向父类。
参考
https://segmentfault.com/a/1190000013105095
http://es6.ruanyifeng.com/#docs/class-extends
以下转载自http://keenwon.com/1524.html
ES5
ES5中的继承,看图:
![](https://img.haomeiwen.com/i7707397/c170e77cd138f8be.png)
function Super() {}
function Sub() {}
Sub.prototype = new Super();
Sub.prototype.constructor = Sub;
var sub = new Sub();
Sub.prototype.constructor === Sub; // ② true
sub.constructor === Sub; // ④ true
sub.__proto__ === Sub.prototype; // ⑤ true
Sub.prototype.__proto__ == Super.prototype; // ⑦ true
ES5中这种最简单的继承,实质上就是将子类的原型设置为父类的实例。
ES6
ES6中的继承,看图:
![](https://img.haomeiwen.com/i7707397/933cc528ee4bed40.png)
class Super {}
class Sub extends Super {}
var sub = new Sub();
Sub.prototype.constructor === Sub; // ② true
sub.constructor === Sub; // ④ true
sub.__proto__ === Sub.prototype; // ⑤ true
Sub.__proto__ === Super; // ⑥ true
Sub.prototype.__proto__ === Super.prototype; // ⑦ true
所以
ES6和ES5的继承是一模一样的,只是多了class 和extends ,ES6的子类和父类,子类原型和父类原型,通过__proto__ 连接。
网友评论