Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

JavaScript Class super Keyword

JavaScript Class super Keyword

JavaScript Class (class) JavaScript Classes (class)


Example

Example

The following example creates a class "Runoob" and uses super to call the constructor of the parent class "Site":

class

Site

{

constructor

(

name

)

{

this

.

sitename

=

name

;

}

present

(

)

{

return

'

I like

'

this

.

sitename

;

}

}

class

Runoob

extends

Site

{

constructor

(

name

,

age

)

{

super

(

name

)

;

this

.

age

=

age

;

}

show

(

)

{

return

this

.

present

(

)

'

, it created

'

this

.

age

'

years.

'

;

}

}

let

noob

=

new

Runoob

(

"

Runoob Tutorial

"

,

5

)

;

document

.

getElementById

(

"

demo

"

)

.

innerHTML

=

noob

.

show

(

)

;

Try it »


Definition and Usage

The super keyword is used to access and call functions on an object's parent object.

When used in a constructor, the super keyword appears on its own and must be used before the this keyword. The super keyword can also be used to call functions on the parent object.

Syntax

super(arguments);  // 调用父构造函数

  super.parentMethod(arguments);  // 调用父方法

  

Technical Details

JavaScript version: ECMAScript 2015 (ES6)

Browser support

super is an ECMAScript6 (ES6) feature.

All major browsers currently support ES6 (JavaScript 2015).

Chrome Edge Firefox Safari Opera
Yes Yes Yes Yes Yes

Internet Explorer 11 or older IE does not support the super keyword.


More examples

Using super in a class:

Example

class

Polygon

{

constructor

(

height

,

width

)

{

this

.

name

=

'

Rectangle

'

;

this

.

height

=

height

;

this

.

width

=

width

;

}

sayName

(

)

{

return

'

Hi, I am a

'

this

.

name

'

.

'

;

}

get

area

(

)

{

return

this

.

height

this

.

width

;

}

set

area

(

value

)

{

this

.

_area

=

value

;

}

}

class

Square

extends

Polygon

{

constructor

(

length

)

{

//

Here, it calls the parent class's constructor,

//

as the height and width of Polygon

super

(

length

,

length

)

;

this

.

height

;

//

need to be placed after super, otherwise a ReferenceError occurs

//

Note: In a derived class, you must call super() before you can use 'this'.

//

Ignoring this will result in a reference error.

this

.

name

=

'

Square

'

;

}

}

Try it »

Call a parent class's static method with super:

Example

class

Rectangle

{

constructor

(

)

{

}

static

logNbSides

(

)

{

return

'

I have 4 sides

'

;

}

}

class

Square

extends

Rectangle

{

constructor

(

)

{

}

static

logDescription

(

)

{

return

super

.

logNbSides

(

)

'

which are all equal

'

;

}

}

Square

.

logDescription

(

)

;

//

'I have 4 sides which are all equal'

Try it »


JavaScript Class (class) JavaScript Classes (class)