35
27

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におけるクラス(es5 vs es6) その1

Last updated at Posted at 2019-02-10

es6__における【classっぽいもの】__の書き方を覚えたので、__es5__の時の書き方と比較しながらアウトプットしたいと思います!

#まずは「es5」で書く!

es5の時には、関数とprototypeというものを使って表現していたらしいです!

function Animal(name,size,cry) {
    this.name = name;
    this.size = size;
    this.cry = cry;
}

Animal.prototype.voice = function () {
    console.log(this.cry);
}

var pig = new Animal('ブタ','LL','ぶひ〜');

pig.voice();
//ぶひ〜

僕みたいな初心者ですと、prototype??ってなります(泣)

#次に「es6」で書く!!
es6ではclass構文が実装され直感的にわかりやすくなったんじゃないかと思います。

class Animal{
    constructor (name,size,cry){  //初期化する時のメソッド
        this.name = name;
        this.size = size;
        this.cry = cry;
    }

    voice() {
        console.log(this.cry);
    }
}

const micropig = new Animal('マイクロミニブタ','s','ぶ〜ぶ〜');

micropig.voice();
//ぶ〜ぶ〜

Animalクラスの中で完結しているのがシンプルで見やすい!

#次回予告
次回は継承の仕方についてまとめます!

35
27
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
35
27

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?