【推荐】2019 Java 开发者跳槽指南.pdf(吐血整理) >>>
ES5
ES5中的继承,看图:
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; // ⑦ truefunction 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中的继承,看图:
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__ 连接。
来源:oschina
链接:https://my.oschina.net/u/1417422/blog/686677