JavaScriptの学習・参考リファレンス/ドキュメント

JavaScript、ECMAScriptの学習と参考メモ 入門~初心者~中級者~上級者を目指して

クラス class

JavaScriptでも他の言語と同じようにclassを定義できます。 ここでは、キーワードclassを使用した定義方法とprototypeベースの定義方法を説明します。

キーワードclassを使用したクラスの定義方法

classの後にクラスの名称を指定します。
コンストラクタはconstructorで引数を持つこともできます。

class Animal {
  
  constructor(weight) {
    this.weight = weight;
  }
  
  getWeight(){
    return this.weight;
  }
}

let animal = new Animal(10);
console.log(animal.getWeight()); // 10

継承はextendsのキーワードを使います。

class Dog extends Animal {
  
  constructor(weight,name) {
    super(weight);
    this.name = name;
  }
  
  getName(){
    return this.name;
  }
}

let dog = new Dog(15,'Hachi');
console.log(dog.getWeight()); // 15
console.log(dog.getName()); // 'Hachi'

prototypeベースの昔のクラスの定義方法

キーワードclassを使わないクラスの定義は次のようになります。

let Animal = function (weight){
  this.weight = weight;
};

Animal.prototype.getWeight = function() {return this.weight;};

let animal = new Animal(10);
console.log(animal.getWeight()); // 10

継承はsetPrototypeOfを使って次のようになります。

let Dog = function (weight,name){
  Animal.call(this, weight);
  this.name = name;
};

Object.setPrototypeOf(Dog.prototype, Animal.prototype);
Animal.prototype.getName = function() {return this.name;};

let dog = new Dog(15,'Hachi');
console.log(dog.getWeight()); // 15
console.log(dog.getName()); // 'Hachi
作成日 : 2020年06月07日