2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

JavaScript~クラスの基本(インスタンス、コンストラクタ、メソッド、継承)

Last updated at Posted at 2019-07-10

#JavaScript~クラスの基本
コピペして使ってください。
ES6を対象としています。

###クラスの定義

sample.js
//クラスの定義
class Animal { 
}
//インスタンスの生成
const animal = new Animal();

###コンストラクタの定義

sample.js
//クラス内にコンストラクタを定義
class Animal {
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }
}

//引数を渡して、インスタンスを生成
const animal = new Animal("ポチ", 8);

console.log(`名前: ${animal.name}`);
console.log(`年齢: ${animal.age}`);

###メソッドの定義

sample.js
class Animal {
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }  
  greet() {
    console.log("こんにちは");
  }
  info(){
    console.log(`名前:${this.name}`);
    console.log(`年齢:${this.age}`);
  }  
}

const animal = new Animal("ポチ", 8);
animal.greet();
animal.info();

###クラスの継承

sample.js
class Animal {
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }  
  greet() {
    console.log("こんにちは");
  }
  info(){
    this.greet();
    console.log(`名前:${this.name}`);
    console.log(`年齢:${this.age}`);
  }    }
}

// Animalクラスを継承してDogクラスを定義
class Dog extends Animal {
  //独自のメソッドを追加できる
    getHumanAge() {
    return this.age*7;
  }
}

//継承元のメソッドを使用できる
const dog = new Animal("ポチ", 3);
dog.info();
//独自のメソッドを使用できる
const humanAge = dog.getHumanAge();
console.log(`人間年齢:${humanAge}`);

###オーバーライド

sample.js
class Animal {
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }
  greet() {
    console.log("こんにちは");
  }
  info() {
    this.greet();
    console.log(`名前は${this.name}です`);
    console.log(`${this.age}歳です`);
  }
}

class Dog extends Animal {
  //constructorを追加
  constructor(name, age, breed) {
    super(name, age);
    this.breed = breed;
  } 
  info() {
    this.greet();
    console.log(`名前:${this.name}`);  
    console.log(`犬種:${this.breed}`);  
    console.log(`年齢:${this.age}`);
    const humanAge = this.getHumanAge();
    console.log(`人間年齢:${humanAge}`);
  } 
  getHumanAge() {
    return this.age * 7;
  }
}

const dog = new Dog("ポチ", 8, "チワワ");
dog.info();

2
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?