LoginSignup
0
0

More than 1 year has passed since last update.

【JavaScript】関数とオブジェクト⑯ クラス

Posted at

はじめに

Udemyの【JS】ガチで学びたい人のためのJavaScriptメカニズムの講座の振り返りです。

前回の記事

目的

  • 関数とオブジェクトについての理解を深める

本題

1.クラス

コンストラクター関数をクラス表記したもの
→ シンタックスシュガー

例1

function Person(name, age) {
  this.name = name;
  this.age = age;
}

Person.prototype.hello = function() {
  console.log('hello ' + this.name);
}

上記のPersonコンストラクターをクラスに書き換えていく

// クラスを用意
class Person {
  // constracterで関数を定義
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }

  // プロトタイプのメソッドも関数と同じ並びに配置
  // function削除
  hello() {
    console.log('hello ' + this.name);
  }
}

// インスタンス化
const Lupin = new Person("ルパン", 26);
// 出力するとPerson {name: 'ルパン', age: 26}で返ってくる
console.log(Lupin);

JavaScriptではインスタンス化したら、オブジェクトで返ってくる

2.クラス継承

クラス継承とは他のクラスのメソッドやプロパティを継承すること

例1.

function Person(name, age) {
  this.name = name;
  this.age = age;
}

Person.prototype.hello = function() {
  console.log('hello ' + this.name);
}

function Japanese(name, age, gender) {
  Person.call(this, name, age);
  this.gender = gender;
}

Japanese.prototype = Object.create(Person.prototype);

Japanese.prototype.hello = function() {
  console.log('Konnichiwa ' + this.name);
}

Japanese.prototype.bye = function() {
  console.log('Sayonara ' + this.name);
}

const taro = new Japanese('Taro', 23, 'Male');

上記のプロトタイプ継承されたコードをクラス継承に変えていく

// Personをクラス表記に変更
class Person{
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }
  // helloメソッド追加
  hello() {
    console.log('hello ' + this.name);
  }
}

// 同様にjapaneseクラスを作成
// Javaでも使用したモノ!
class Japanese extends Person{
  constructor(name, age, gender) {
    // クラスの継承では下記を使用していたが、クラスではextendsを使用
    // Person.call(this, name, age);
    // superを使用することで継承元のプロパティを使用できる
    super(name, age);
    this.gender = gender;
  }
  // helloメソッドを追加
  hello(){
    console.log('Konnichiwa ' + this.name);
  }
  // byeメソッドを追加
  bye() {
    console.log('Sayonara ' + this.name);
  }
}
// 下記のコードもextendsによって実現されるので不要
// Japanese.prototype = Object.create(Person.prototype);

// インスタンス化
const taro = new Japanese('Taro', 23, 'Male');
// 出力するとオブジェクトが生成される
console.log(taro);
// taroメソッドが使用される
taro.hello();

今日はここまで!

参考にさせて頂いた記事

0
0
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
0
0