JavaScript Reference ยท Operators
The super keyword
Reference for the JavaScript super keyword: super() in derived constructors, super.method() calls, object literals, static methods and common errors.
super gives code in a class (or object literal method) access to the parent. It has two forms. super(...) calls the parent constructor and is allowed only inside the constructor of a derived class. super.name looks up a property or method on the parent prototype, so a subclass can extend an inherited method instead of replacing it.
class Dog extends Animal { constructor(name) { super(name); // call the parent constructor } speak() { return super.speak() + " Woof."; // call the parent method } }
Try it
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Syntax
super(...args) // derived class constructors only super.prop super[expression] super.method(...args)
| Form | Description |
|---|---|
super(...args) |
Calls the parent constructor with this bound to the new object being created and initializes this. Returns this. |
super.prop, super[expr] |
Reads a property from the parent's prototype (or the parent class itself, inside static methods). |
super.method(...) |
Calls the parent's method with the current this. |
Return value: super(...) returns the initialized this value. super.prop evaluates to the property value.
Exceptions: a derived constructor that uses this before super() throws a ReferenceError, as does one that finishes without calling super() (unless it returns an object). Calling super() twice throws a ReferenceError. super is a SyntaxError outside methods.
Usage notes
- Call
super()first in a derived constructor, before touchingthis. You may run code before it as long as it does not usethis. thisstays the instance.super.method()runs the parent's method, butthisinside is still the current object.- Assignments through
super.prop = valueset the property onthis, not on the parent prototype. This surprises people; avoid it. - Arrow functions inside a method can use
superbecause they inherit it from the enclosing method. - Allowed in method shorthand, including object literal methods and static methods, but not in regular
functionproperties like{ f: function () { super.x } }. - Home object is fixed. A method's
superrefers to the prototype of the object it was defined on; copying the method to another object does not change that. - Built-in subclassing.
class MyArray extends Arrayworks becausesuper()allocates the exotic array object. - Not usable as a value.
const s = super;is a syntax error.
Browser support
Supported in every current browser (ES2015).
Related
- class statement
- new.target
- this keyword
- Lessons: Classes, Inheritance