博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
JavaScript super关键字
阅读量:2506 次
发布时间:2019-05-11

本文共 2010 字,大约阅读时间需要 6 分钟。

When we work with classes in JavaScript, it’s common to use the super keyword.

当我们使用JavaScript处理类时,通常使用super关键字。

In this post I want to clarify what’s it useful for.

在这篇文章中,我想阐明它的作用。

Suppose you have a class Car:

假设您有一个Car类:

class Car {}

and in this class we have a constructor() method:

在这个类中,我们有一个constructor()方法:

class Car {  constructor() {    console.log('This is a car')  }}

The constructor method is special because it is executed when the class is instantiated:

构造函数方法很特殊,因为它在实例化类时执行:

const myCar = new Car() //'This is a car'

You can have a Tesla class that extends the Car class:

您可以拥有扩展Car类的Tesla类:

class Tesla extends Car {}

The Tesla class inherited all the methods and properties of Car, including the constructor method.

Tesla类继承了Car所有方法和属性,包括constructor方法。

We can create an instance of the Tesla class, creating a new myCar object:

我们可以创建Tesla类的实例,创建一个新的myCar对象:

const myCar = new Tesla()

And the original constructor in Car is still executed, because Tesla does not have one of its own.

Car的原始构造函数仍在执行,因为Tesla没有自己的构造函数。

We can override the constructor() method in the Tesla class:

我们可以在Tesla类中重写constructor()方法:

class Tesla extends Car {  constructor() {    console.log('This is a Tesla')  }}

and

const myCar = new Tesla()

will print This is a Tesla.

将打印This is a Tesla

In the constructor() method we can also call super() to invoke the same method in the parent class:

constructor()方法中,我们还可以调用super()来调用父类中的相同方法:

class Tesla extends Car {  constructor() {    super()    console.log('This is a Tesla')  }}

Calling

呼唤

const myCar = new Tesla()

will now execute 2 console logs. First the one defined in the Car class constructor, the second the one defined in the Tesla class constructor:

现在将执行2个控制台日志。 第一个是在Car类构造函数中定义的,第二个是在Tesla类构造函数中定义的:

'This is a car''This is a Tesla'

Note that super() can only be called in the constructor, not in other methods.

请注意,只能在构造函数中调用super() ,而不能在其他方法中调用。

And we can pass in any parameter, if the constructor accepts parameters.

如果构造函数接受参数,我们可以传入任何参数。

翻译自:

转载地址:http://nxmgb.baihongyu.com/

你可能感兴趣的文章
Object 一些方法
查看>>
数组比较大小的几种方法及math是方法
查看>>
FTP站点建立 普通电脑版&&服务器版
查看>>
js 给一段代码,给出运行后的最终结果的一些综合情况、
查看>>
webservice 详解
查看>>
js自动补全实例
查看>>
VS无法启动调试:“生成下面的模块时,启用了优化或没有调试信息“
查看>>
npm 安装 sass=-=-=
查看>>
WINFORM中加入WPF控件并绑定数据源实现跨线程自动更新
查看>>
C#类对象的事件定义
查看>>
各类程序员学习路线图
查看>>
HDU 5510 Bazinga KMP
查看>>
关于select @@IDENTITY的初识
查看>>
ASP.NET MVC ajax提交 防止CSRF攻击
查看>>
关于CSS伪类选择器
查看>>
适用于带文字 和图片的垂直居中方法
查看>>
Part 2 - Fundamentals(4-10)
查看>>
使用Postmark测试后端存储性能
查看>>
NSTextView 文字链接的定制化
查看>>
第五天站立会议内容
查看>>