https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Classes
- ECMAScript 6で追加された
- 昔はprototypeを利用してクラス的な振る舞いをするオブジェクトを作成することが多かったが、class構文を使えば簡単にクラスを扱うことができる
class Polygon { constructor(height, width) { this.height = height; this.width = width; } get area() { return this.calcArea(); } calcArea() { return this.height * this.width; } } const square = new Polygon(10, 10); console.log(square.area); // 100
- 同じclass名で重複して定義するとエラーとなる
class Animal{ constructor(){ this.name = 'animal' } }; class Animal{}; // VM338:1 Uncaught SyntaxError: Identifier 'Animal' has already been declared // at <anonymous>:1:1
-
NG
Animal() // VM344:1 Uncaught TypeError: Class constructor Animal cannot be invoked without 'new' // at <anonymous>:1:1
-
OK
new Animal() // Animal {name: "animal"}
- インスタンスから直接呼び出すことは出来ない
- クラスから呼び出して使用する
class Animal{ constructor(){ this.name = 'animal' } static run(){ console.log('running!'); } sound(){ console.log('blah'); } } const some_animal = new Animal(); some_animal.run() // VM405:1 Uncaught TypeError: some_animal.run is not a function // at <anonymous>:1:13 Animal.prototype.run() // VM413:1 Uncaught TypeError: Animal.prototype.run is not a function // at <anonymous>:1:1 Animal.run() // running!
- Javaっぽい書き方
class Dog extends Animal { constructor(name){ this.name = name } sound(){ console.log('wan'); } }; let pochi = new Dog('pochi'); pochi.sound(); // wan Dog.run() // running
-
内部的には昔ながらのプロトタイプチェーンによって実現されている
typeof(Dog) // "function" typeof(pochi) // "object"
pochi.constructor === Dog // true pochi.constructor.__proto__ === Animal // true pochi.constructor.__proto__.__proto__ === Function.prototype // true pochi.constructor.__proto__.__proto__.__proto__ === Object.prototype // true
pochi.__proto__ === Dog.prototype // true pochi.__proto__.__proto__ === Animal.prototype // true pochi.__proto__.__proto__.__proto__ === Object.prototype // true
- ただし、classはnew演算子無しで呼び出すとエラーになるなどの点でコンストラクタ関数とは異なっている