ES5和ES6中的继承

Javascript中的继承一直是个比较麻烦的问题,prototype、constructor、__proto__在构造函数,实例和原型之间有的复杂的关系,不仔细捋下很难记得牢固。ES6中又新增了class和extends,和ES5搅在一起,加上平时很少自己写继承,简直乱成一锅粥。不过还好,画个图一下就清晰了,下面不说话了,直接上图,上代码。

 

 

  1. function Super() {}
  2.  
  3. function Sub() {}
  4. Sub.prototype = new Super();
  5. Sub.prototype.constructor = Sub;
  6.  
  7. var sub = new Sub();
  8.  
  9. Sub.prototype.constructor === Sub; // ② true
  10. sub.constructor === Sub; // ④ true
  11. sub.__proto__ === Sub.prototype; // ⑤ true
  12. Sub.prototype.__proto__ == Super.prototype; // ⑦ true

 

 

ES6

ES6中的继承,看图:

  1. class Super {}
  2.  
  3. class Sub extends Super {}
  4.  
  5. var sub = new Sub();
  6.  
  7. Sub.prototype.constructor === Sub; // ② true
  8. sub.constructor === Sub; // ④ true
  9. sub.__proto__ === Sub.prototype; // ⑤ true
  10. Sub.__proto__ === Super; // ⑥ true
  11. Sub.prototype.__proto__ === Super.prototype; // ⑦ true

 

posted on 2016-12-04 14:12  1883808  阅读(553)  评论(0编辑  收藏  举报