ES5和ES6中的繼承

ES5

ES5中的繼承,看圖:prototype

輸入圖片說明

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中這種最簡單的繼承,實質上就是將子類的原型設置爲父類的實例。code

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__ 鏈接。圖片

相關文章
相關標籤/搜索