class
Baseline
Widely available
This feature is well established and works across many devices and browser versions. Itâs been available across browsers since 2017å¹´3æ.
class 宣è¨ã¯ãæå®ãããååã®æ°ãã class ã使ãã¾ãã
ã¯ã©ã¹å¼ ã使ã£ã¦ã¯ã©ã¹ãå®ç¾©ã§ãã¾ãã
試ãã¦ã¿ã¾ããã
class Polygon {
constructor(height, width) {
this.area = height * width;
}
}
console.log(new Polygon(4, 3).area);
// Expected output: 12
æ§æ
class name {
// ã¯ã©ã¹æ¬ä½
}
class name extends otherName {
// ã¯ã©ã¹æ¬ä½
}
解説
ã¯ã©ã¹å®£è¨ã®ã¯ã©ã¹æ¬ä½ã¯ 峿 ¼ã¢ã¼ã ã§å®è¡ããã¾ããã¯ã©ã¹å®£è¨ã¯ let ã¨é常ã«ããä¼¼ã¦ãã¾ãã
-
class宣è¨ã¯ã颿°ã ãã§ãªããããã¯ã«ãã¹ã³ã¼ãããã¾ãã -
class宣è¨ã¯ã宣è¨ãããå ´æã«å°éããå¾ã«ã®ã¿ã¢ã¯ã»ã¹ã§ãã¾ãï¼ä¸æçãããã¾ã¼ã³ ãåç §ï¼ããã®ãããclass宣è¨ã¯ä¸è¬çã« éãã¤ã¹ãã£ã³ã° ã¨ã¿ãªããã¾ãï¼é¢æ°å®£è¨ ã¨ã¯ç°ãªãã¾ãï¼ã -
ã¹ã¯ãªããã®æä¸ä½ã¬ãã«ã§å®£è¨ããã
class宣è¨ã¯ãglobalThisã«ããããã£ã使ãã¾ããï¼é¢æ°å®£è¨ ã¨ã¯ç°ãªãã¾ãï¼ã -
class宣è¨ã¯ãåãã¹ã³ã¼ãå ã®ä»ã®å®£è¨ã«ãã£ã¦ åå®£è¨ ã§ãã¾ããã
class Foo {
static {
Foo = 1; // TypeError: Assignment to constant variable.
}
}
class Foo2 {
bar = (Foo2 = 1); // TypeError: Assignment to constant variable.
}
class Foo3 {}
Foo3 = 1;
console.log(Foo3); // 1
ä¾
>ã¯ã©ã¹å®£è¨
次ã®ä¾ã§ã¯ãã¯ããã« Rectangle ã¨ããååã®ã¯ã©ã¹ãå®ç¾©ããæ¬¡ã«ãããæ¡å¼µã㦠FilledRectangle ã¨ããååã®ã¯ã©ã¹ã使ãã¾ãã
ãªããã³ã³ã¹ãã©ã¯ã¿ã¼ (constructor) ã§ä½¿ããã¦ãã super() ã¯ãã³ã³ã¹ãã©ã¯ã¿ã¼å
ã§ã®ã¿ä½¿ãããã¨ã this ãã¼ã¯ã¼ãã®ä½¿ç¨åã«å¼ã³åºããªãã¦ã¯ãªããªããã¨ã«æ³¨æãã¦ãã ããã
class Rectangle {
constructor(height, width) {
this.name = "Rectangle";
this.height = height;
this.width = width;
}
}
class FilledRectangle extends Rectangle {
constructor(height, width, color) {
super(height, width);
this.name = "Filled rectangle";
this.color = color;
}
}
仿§æ¸
| Specification |
|---|
| ECMAScript® 2027 Language Specification> # sec-class-definitions> |