Javascript中的繼承一直是個比較麻煩的問題,prototype、constructor、__proto__在構造函數,實例和原型之間有的複雜的關係,不仔細捋下很難記得牢固。ES6中又新增了class和extends,和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; // ⑦ true
ES6
ES6中的繼承,看圖:spa
- 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