Home > Article > Web Front-end > What does the es6 keyword super mean?
In es6, super means "super". This keyword can be used as a function or an object: 1. When used as a function, it represents the constructor of the parent class, and the syntax is: "constructor(){super();}"; 2. When used as an object, it represents the prototype object of the parent class.
The operating environment of this tutorial: Windows 10 system, ECMAScript version 6.0, Dell G3 computer.
ES6 re-implements class inheritance, and in the process of inheritance, the super keyword plays a vital role. It can be said that super cannot be understood keyword, you cannot master the inheritance of classes. Today we will discuss the keyword super.
First of all, throw out a concept: The keyword super can both It can be used as a function or as an object
The first case: when super is used as a function, it represents the constructor of the parent class
ES6 requires that the constructor of a subclass must be executed once super
Function
class A {}class B extends A { constructor() { super();//子类的构造函数,必须执行一次super函数,代表父类的构造函数 }}
Note: Although super represents the constructor of the parent class, what is returned at this time is B's Instance, that is, this inside super refers to the instance of B, so super()
is equivalent to A.prototype.constructor.call(this)
In the above code, new.target
points to the currently executing function. When super() is executed, it points to the constructor of subclass B, not parent class A. constructor, that is to say, this inside super() points to B
The second case: when super is used as an object, in the ordinary method , pointing to the prototype object of the parent class, in the static method, pointing to the parent class
class A { p() { return 2; }}class B extends A { constructor() { super();//父类的构造函数 console.log(super.p()); // 2 }}let b = new B();
In the above code, super
, when used as a function, represents the constructor of the parent class , when used as an object, points to the prototype object of the parent class, that is, A.prototype
, so super.p()
is equivalent to A.prototype.p()
It should also be noted here that since super points to the prototype of the parent class, the properties or methods on the parent class instance cannot be called through super
In the above code, p is an attribute of the instance of parent class A, so super.p
cannot refer to it
[Related Recommended: javascript video tutorial, web front-end】
The above is the detailed content of What does the es6 keyword super mean?. For more information, please follow other related articles on the PHP Chinese website!