Baseline Widely available
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"
è§è æµè§å¨å
¼å®¹æ§ åè§
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4