Advertisement
Guest User

Untitled

a guest
Aug 17th, 2019
66
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.02 KB | None | 0 0
  1. ES5和ES6的继承有什么区别?
  2.  
  3. MA:
  4. 1. ES5的继承一般是通过原型链模式或者构造函数模式来实现继承的,比如
  5. ```js
  6. // 原型链模式
  7. function Parent () {}
  8. function Sub () {}
  9. Sub.prototype = new Parent()
  10. Sub.constructor = Sub
  11. var sub = new Sub();
  12. Sub.__proto__ === Function.prototype
  13. // 构造模式
  14. function Parent () {}
  15. function Sub () {
  16. Parent.apply(this, arguments)
  17. }
  18. var sub = new Sub();
  19. Sub.__proto__ === Function.prototype
  20. ```
  21. 通过上面的举例,可以看到,ES5的的子构造函数的 `prototype` 指向的是 `Function.prototype`。
  22. 而 ES6 实现的继承,`Sub.prototype` 的会指向 `Parent`。
  23. ```js
  24. class Parent {}
  25. class Sub extends Parent {
  26. constructor(){
  27. super()
  28. }
  29. }
  30.  
  31. Sub.__proto__ === Parent
  32. ```
  33.  
  34. 2. this 的构造顺序是不一样的,ES5 的继承是先构造子对象然后再产生父对象,然后将父对象里面的属性复制到子对象中。而 ES6 是先使用 `super()`创建
  35. 父对象,然后再创建子对象。所以 this 的构造顺序不同。
  36.  
  37. OA:
  38.  
  39. 1. ES5 和 ES6 子类 this 生成顺序不同。ES5 的继承先生成了子类实例,再调用父类的构造函数修饰子类实例,ES6 的继承先生成父类实例,再调用子类的构造函数修饰父类实例。这个差别使得 ES6 可以继承内置对象。
  40. ```js
  41. function MyES5Array() {
  42. Array.call(this, arguments);
  43. }
  44.  
  45. // it's useless
  46. const arrayES5 = new MyES5Array(3); // arrayES5: MyES5Array {}
  47.  
  48. class MyES6Array extends Array {}
  49.  
  50. // it's ok
  51. const arrayES6 = new MyES6Array(3); // arrayES6: MyES6Array(3) []
  52. ```
  53.  
  54. 2. 问题是继承的差异。
  55. ```js
  56. class Super {}
  57. class Sub extends Super {}
  58.  
  59. const sub = new Sub();
  60.  
  61. Sub.__proto__ === Super;
  62. ```
  63. 子类可以直接通过 `__proto__` 寻址到父类。
  64. ```js
  65. function Super() {}
  66. function Sub() {}
  67.  
  68. Sub.prototype = new Super();
  69. Sub.prototype.constructor = Sub;
  70.  
  71. var sub = new Sub();
  72.  
  73. Sub.__proto__ === Function.prototype;
  74. ```
  75. 而通过 ES5 的方式,`Sub.__proto__ === Function.prototype`
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement