taquaki-satwo
12/11/2017 - 11:28 AM

ES6クラス公文

JS-ES6クラス公文

/*
# クラス宣言
* 巻き上げしない
* 同じクラス名で宣言文を記述するとタイプエラー
* 関数としては呼び出せない
*/
class Circle {
  constructor(center, radius) {
    this.center = center;
    this.radius = radius;
  }

  area() {
    return Math.PI * this.radius * this.radius;
  }
}

const c = new Circle({ x: 0, y: 0 }, 2);
console.log(c.area());
console.log(Circle);
console.log(c.__proto__);

/*
# クラス式
* 巻き上げしない
* 同じ名前で複数回定義できる
*/
const Circle2 = class {
  constructor(center, radius) {
    this.center = center;
    this.radius = radius;
  }
  area() {
    return Math.PI * this.radius * this.radius;
  }
};
// 識別子をつけることができる
// const Circle2 = class Kreis { ... };
// * 名前はクラス本体の中でのみ有効
// * 実行時代入なので巻き上げられない
// * 同じ名前で複数回クラス式による定義ができる

/*
# アクセッサ
*/
class Person {
  constructor(name) {
    this.name = name;
  }
  get name() {
    return this._name;
  }
  set name(value) {
    this._name = value;
  }
  sayName() {
    console.log(this.name);
  }
}

const person = new Person('Tom');
console.log(person.name);
person.name = 'Huck';
console.log(person.name);
person.sayName();

console.log(Person);
console.log(person);
console.log(person.__proto__);


/*
# 静的メソッド
インスタンスを生成せずに実行できるメソッドのこと
*/
class Person2 {
  constructor(name) {
    this.name = name;
    Person2.personCount++;
  }
  get name() {
    return this._name;
  }
  set name(value) {
    this._name = value;
  }
  sayName() {
    console.log(this.name);
  }
  static count() {
    return Person2.personCount;
  }
}
Person2.personCount = 0;

var person2_1 = new Person2('Tom');
console.log(Person2.count()); // -> 1
var person2_2 = new Person2('Hack');
console.log(Person2.count()); // -> 2

/*
# 継承
* 実際はprototype継承し、新しいメソッドを追加するというもの
* プロパティの構成は変えない
*/
class Circle3 {
  constructor(center, radius) {
    this.center = center;
    this.radius = radius;
  }
  area() {
    return Math.PI * this.radius * this.radius;
  }
  toString() {
    return `Circle center: x:${this.center.x} y:${this.center.y}, radius: ${this.radius}`;
  }
}

class Ball extends Circle3 {
  move(dx, dy) {
    this.center.x += dx;
    this.center.y += dy;
  }
}

var ball = new Ball({x: 0, y:0}, 2);
console.log(ball.toString());
console.log(ball.area());
ball.move(1, 2);
console.log(ball.toString());

/*
# スーパータイプのメソッドを呼び出す
*/
class Ball2 extends Circle3 {
   move(dx, dy) {
    this.center.x += dx;
    this.center.y += dy;
  }
  toString() {
    var str = super.toString();
    return str.replace('Circle', 'Ball');
  }
}

var ball2 = new Ball2({x: 0, y: 0}, 2);
console.log(ball2.toString());

JS-ES6クラス公文

A Pen by Takaaki Sato on CodePen.

License.