类表达å¼
åºçº¿
广æ³å¯ç¨
èª 2016å¹´3æ èµ·ï¼æ¤ç¹æ§å·²å¨ä¸»æµæµè§å¨ä¸å¾å°æ¯æï¼å¯å¨å¤§å¤æ°è®¾å¤åæµè§å¨çæ¬ä¸æ£å¸¸ä½¿ç¨ã
class å
³é®åå¯ç¨äºå¨è¡¨è¾¾å¼ä¸å®ä¹ç±»ã类似äºå½æ°è¡¨è¾¾å¼ï¼ç±»è¡¨è¾¾å¼å¯ä»¥æ¯å½åçï¼ä¹å¯ä»¥æ¯å¿åçã妿å½åï¼åç±»çåç§°åªè½å¨ç±»ä½å
鍿è½è®¿é®å°ã
å°è¯ä¸ä¸
const Rectangle = class {
constructor(height, width) {
this.height = height;
this.width = width;
}
area() {
return this.height * this.width;
}
};
console.log(new Rectangle(5, 8).area());
// Expected output: 40
è¯æ³
const MyClass = class [className] [extends otherClassName] {
// class body
}
æè¿°
类表达å¼çè¯æ³ç±»ä¼¼äºç±»å£°æãä¸ class 声æä¸æ ·ï¼class 表达å¼ç主ä½å¨ä¸¥æ ¼æ¨¡å¼ä¸æ§è¡ã
类表达å¼å类声æä¹é´åå¨ä¸äºå·®å¼ï¼ä½æ¯ï¼
- 类表达å¼å¯ä»¥çç¥ç±»åï¼âç»å®æ è¯ç¬¦âï¼ï¼è¿å¨ç±»å£°æä¸æ¯ä¸å¯è½çã
- 类表达å¼å
è®¸ä½ éæ°å®ä¹ï¼éæ°å£°æï¼ç±»èä¸ä¼æåº
SyntaxErrorã类声æä¸æ¯è¿ç§æ åµã
constructor æ¹æ³æ¯å¯éçã使ç¨ç±»è¡¨è¾¾å¼çæçç±»å°å§ç»ååº typeof å¼ä¸º "function"ã
"use strict";
let Foo = class {}; // constructor property is optional
Foo = class {}; // Re-declaration is allowed
typeof Foo; // returns "function"
typeof class {}; // returns "function"
Foo instanceof Object; // true
Foo instanceof Function; // true
class Foo {} // Throws SyntaxError (class declarations do not allow re-declaration)
示ä¾
>ä¸ä¸ªç®åç类表达å¼
è¿åªæ¯ä¸ä¸ªç®åçå¿å类表达å¼ï¼ä½ å¯ä»¥ä½¿ç¨åé Foo æ¥å¼ç¨å®ã
const Foo = class {
constructor() {}
bar() {
return "Hello World!";
}
};
const instance = new Foo();
instance.bar(); // "Hello World!"
Foo.name; // "Foo"
å½å类表达å¼
å¦æä½ æ³å¨ç±»ä½å å¼ç¨å½åç±»ï¼ä½ å¯ä»¥å建ä¸ä¸ªå½å类表达å¼ã该åç§°ä» å¨ç±»è¡¨è¾¾å¼æ¬èº«çèå´å å¯è§ã
const Foo = class NamedFoo {
constructor() {}
whoIsThere() {
return NamedFoo.name;
}
};
const bar = new Foo();
bar.whoIsThere(); // "NamedFoo"
NamedFoo.name; // ReferenceError: NamedFoo is not defined
Foo.name; // "NamedFoo"
è§è
| è§è |
|---|
| ECMAScript® 2027 Language Specification> # sec-class-definitions> |