当前位置:网站首页>继承的实现过程及ES5和ES6实现的区别
继承的实现过程及ES5和ES6实现的区别
2022-07-25 15:00:00 【Henry_楠】
ES5的继承方法可以看这篇:ES5写继承的思路
ES5与ES6的继承方法对照:
ES5
function Parent() {
this.name = 'parent';
this.arr = [1,2,3,4];
}
Parent.prototype.say = function () {
console.log('say');
};
function Child(age) {
Parent.call(this);
this.age = age;
}
Child.prototype = Object.create(Parent.prototype);
Child.prototype.constructor = Child;
var c = new Child(12);
console.log(c.name); //输出parent
c.say(); //输出say
console.log(c.constructor); //输出function Child(age) {Parent.call(this);this.age = age;}
console.log(new Parent().constructor); //输出Parent() {this.name = 'parent';this.arr = [1,2,3,4];}
ES6
class Parent2 {
constructor() {
this.name = 'parent';
}
}
Parent2.prototype.say = function () {
console.log('say');
};
class Child2 extends Parent {
constructor(age) {
super();
this.age = age;
}
}
var c2 = new Child2(12);
console.log(c2.name); //输出parent
c2.say(); //输出say
console.log(c.constructor); //输出function Child(age) {Parent.call(this);this.age = age;}
console.log(new Parent().constructor); //输出Parent() {this.name = 'parent';this.arr = [1,2,3,4];}
- ES5的继承实质上是先创建子类的实例对象,然后再将父类的方法添加到this上(Parent.apply(this)),然后再把原型链继承。
- ES6的继承机制完全不同,实质上是先创建父类的实例对象this(所以必须先调用父类的super()方法,才可使用this关键字,否则报错。),然后再用子类的构造函数修改this实现继承。
ps:es5及以下无法完美继承array,相关内容可自行搜索
边栏推荐
- 关于RDBMS和非RDBMS【数据库系统】
- node学习
- IP address classification, which determines whether a network segment is a subnet supernetwork
- Is it safe for Guolian securities to buy shares and open an account?
- 37 元素模式(行内元素,块元素,行内块元素)
- I2C device driver hierarchy
- kibana操作es
- sql server强行断开连接
- L1 and L2 regularization
- 27 classification of selectors
猜你喜欢

L1和L2正则化

Nacos2.1.0 cluster construction

41 图片背景综合-五彩导航图

【MySQL系列】-索引知多少

Leetcode combination sum + pruning

Sudo rosdep init error ROS installation problem solution

As methods for viewing and excluding dependencies

Syntax summary of easygui

Implement a simple restful API server

I hope some suggestions on SQL optimization can help you who are tortured by SQL like me
随机推荐
Several methods of spark parameter configuration
Browser based split screen reading
The solution to the problem that the progress bar of ros2 installation connext RMW is stuck at 13%
kibana操作es
When using jetty to run items, an error is reported: form too large or form too many keys
EDA chip design solution based on AMD epyc server
006操作符简介
瀑布流布局
Yarn: the file yarn.ps1 cannot be loaded because running scripts is prohibited on this system.
Sudo rosdep init error ROS installation problem solution
Jmeter的随机数函数怎么用
Share a department design method that avoids recursion
27 选择器的分类
Implementation of redis distributed lock
51 single chip microcomputer learning notes (1)
LeetCode-198-打家劫舍
MySQL sort
解决asp.net上传文件时文件太大导致的错误
Add the jar package under lib directory to the project in idea
TypeScript学习2——接口