class å¼
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æ.
class ãã¼ã¯ã¼ãã使ç¨ããã¨ãå¼å
ã§ã¯ã©ã¹ãå®ç¾©ãããã¨ãã§ãã¾ãã
ã¯ã©ã¹ã¯ã 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());
// äºæ³ãããçµæ: 40
æ§æ
class {
// ã¯ã©ã¹æ¬ä½
}
class name {
// ã¯ã©ã¹æ¬ä½
}
ã¡ã¢:
弿 ã¯ãclass å®£è¨ ã¨ã®ææ§ããé¿ããããããã¼ã¯ã¼ã class ã§å§ãã¦ã¯ãªãã¾ãããclass ãã¼ã¯ã¼ãã¯ãæãåãå
¥ããªãã³ã³ããã¹ãã§ç¾ããå ´åã«ã®ã¿ãå¼ãéå§ãã¾ãã
解説
class å¼ã¯ãclass 宣è¨ã¨ããä¼¼ã¦ãããæ§æãã»ã¼åãã§ãã class 宣è¨ã¨åæ§ã«ã class å¼ã®æ¬ä½ã¯å³æ ¼ã¢ã¼ãã§å®è¡ããã¾ãã class å¼ã¨ class 宣è¨ã®ä¸»ãªéãã¯ãã¯ã©ã¹åã§ãã class å¼ã§ã¯ãã®ã¯ã©ã¹åãçç¥ã§ãããããç¡åã¯ã©ã¹ã使ãããã¨ãã§ãã¾ããã¯ã©ã¹å¼ã¯ã¯ã©ã¹ãåå®ç¾©ã§ãã¾ããã class 宣è¨ã使ç¨ãã¦ã¯ã©ã¹ãå宣è¨ããã¨ã SyntaxError ãçºçãã¾ãã詳細ã«ã¤ãã¦ã¯ãã¯ã©ã¹ã®ç« ãåç
§ãã¦ãã ããã
ä¾
>ç°¡åãªã¯ã©ã¹å¼
以ä¸ã¯ãååã®ãªãç°¡åãªã¯ã©ã¹å¼ã§ãã夿° 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"
仿§æ¸
| Specification |
|---|
| ECMAScript® 2027 Language Specification> # sec-class-definitions> |