Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- ES5和ES6的继承有什么区别?
- MA:
- 1. ES5的继承一般是通过原型链模式或者构造函数模式来实现继承的,比如
- ```js
- // 原型链模式
- function Parent () {}
- function Sub () {}
- Sub.prototype = new Parent()
- Sub.constructor = Sub
- var sub = new Sub();
- Sub.__proto__ === Function.prototype
- // 构造模式
- function Parent () {}
- function Sub () {
- Parent.apply(this, arguments)
- }
- var sub = new Sub();
- Sub.__proto__ === Function.prototype
- ```
- 通过上面的举例,可以看到,ES5的的子构造函数的 `prototype` 指向的是 `Function.prototype`。
- 而 ES6 实现的继承,`Sub.prototype` 的会指向 `Parent`。
- ```js
- class Parent {}
- class Sub extends Parent {
- constructor(){
- super()
- }
- }
- Sub.__proto__ === Parent
- ```
- 2. this 的构造顺序是不一样的,ES5 的继承是先构造子对象然后再产生父对象,然后将父对象里面的属性复制到子对象中。而 ES6 是先使用 `super()`创建
- 父对象,然后再创建子对象。所以 this 的构造顺序不同。
- OA:
- 1. ES5 和 ES6 子类 this 生成顺序不同。ES5 的继承先生成了子类实例,再调用父类的构造函数修饰子类实例,ES6 的继承先生成父类实例,再调用子类的构造函数修饰父类实例。这个差别使得 ES6 可以继承内置对象。
- ```js
- function MyES5Array() {
- Array.call(this, arguments);
- }
- // it's useless
- const arrayES5 = new MyES5Array(3); // arrayES5: MyES5Array {}
- class MyES6Array extends Array {}
- // it's ok
- const arrayES6 = new MyES6Array(3); // arrayES6: MyES6Array(3) []
- ```
- 2. 问题是继承的差异。
- ```js
- class Super {}
- class Sub extends Super {}
- const sub = new Sub();
- Sub.__proto__ === Super;
- ```
- 子类可以直接通过 `__proto__` 寻址到父类。
- ```js
- function Super() {}
- function Sub() {}
- Sub.prototype = new Super();
- Sub.prototype.constructor = Sub;
- var sub = new Sub();
- Sub.__proto__ === Function.prototype;
- ```
- 而通过 ES5 的方式,`Sub.__proto__ === Function.prototype`
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement