super
Baseline
Widely available
This feature is well established and works across many devices and browser versions. Itâs been available across browsers since 2016å¹´3æ.
super ééµåè¢«ä½¿ç¨æ¼ééå½å¼ååç¶å±¤
super.prop è super[expr] è¡¨éææå¨ method definition è classes è object literals.
èªæ³
super([arguments]); // calls the parent constructor. super.functionOnParent([arguments]);
æè¿°
ç¶ä½¿ç¨å»ºæ§åï¼super ééµåå¿
é åºç¾å¨this ééµåä¹å使ç¨ï¼super ééµåä¹å¯ä»¥ä½¿ç¨å¨å¼å«å½å¼èç¶å°è±¡
ç¯ä¾
>å¨é¡å¥ä¸ä½¿ç¨ super
éåç¨å¼ç¢¼çæ®µå¾ classes sample (live demo). éè£ç super() 被å¼å«å»é¿å
è¤è£½å°å»ºæ§åç Rectangle è Square çå
±éé¨åã
class Rectangle {
constructor(height, width) {
this.name = "Rectangle";
this.height = height;
this.width = width;
}
sayName() {
console.log("Hi, I am a ", this.name + ".");
}
get area() {
return this.height * this.width;
}
set area(value) {
this.area = value;
}
}
class Square extends Rectangle {
constructor(length) {
this.height; // ReferenceError, super needs to be called first!
// Here, it calls the parent class's constructor with lengths
// provided for the Rectangle's width and height
super(length, length);
// Note: In derived classes, super() must be called before you
// can use 'this'. Leaving this out will cause a reference error.
this.name = "Square";
}
}
Super-calling éæ æ¹æ³
ä½ ä¹å¯ä»¥ä½¿ç¨å¨éæ æ¹æ³.
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'
åªé¤ super 屬æ§å°æåºé¯èª¤
ä½ ä¸è½ä½¿ç¨ delete operator 以å super.prop 以å super[expr] å»åªé¤ç¶å±¤çé¡å¥å±¬æ§, ä¸ç¶ä»æä¸åºä¸åé¯èª¤ ReferenceError.
class Base {
constructor() {}
foo() {}
}
class Derived extends Base {
constructor() {}
delete() {
delete super.foo; // this is bad
}
}
new Derived().delete(); // ReferenceError: invalid delete involving 'super'.
super.prop ä¸è½è¤å¯«å¨ä¸è½è¤å¯«ç屬æ§
ç¶å®ç¾©ä¸å¯å¯«å±¬æ§ï¼ä¾å¦ Object.defineProperty, super ä¸è½è¤å¯«éå屬æ§çå¼.
class X {
constructor() {
Object.defineProperty(this, "prop", {
configurable: true,
writable: false,
value: 1,
});
}
}
class Y extends X {
constructor() {
super();
}
foo() {
super.prop = 2; // Cannot overwrite the value.
}
}
var y = new Y();
y.foo(); // TypeError: "prop" is read-only
console.log(y.prop); // 1
ä½¿ç¨ super.prop å¨å°è±¡ç¬¦è
Super å¯ä»¥ä½¿ç¨å¨ object initializer / literal 符è. å¨éåç¯ä¾, æå
©åå°è±¡å®ç¾©å¨ä¸åæ¹æ³. å¨ç¬¬äºåå°è±¡è£¡é¢, super å¼å«äºç¬¬ä¸åå°è±¡çæ¹æ³. éååä½å¹«å© Object.setPrototypeOf() è®æåå¯ä»¥è¨å®åå obj2 to obj1, æä»¥ super å¯ä»¥ç¼ç¾ method1 å¨ obj1裡被æ¾å°.
var obj1 = {
method1() {
console.log("method 1");
},
};
var obj2 = {
method2() {
super.method1();
},
};
Object.setPrototypeOf(obj2, obj1);
obj2.method2(); // logs "method 1"
è¦æ ¼
| Specification |
|---|
| ECMAScript® 2027 Language Specification> # sec-super-keyword> |