コピペコードで快適生活

明日使えるソースを自分のために

Javascriptのオブジェクト指向について

Javascript書くときに雰囲気でオブジェクト指向してたので復習。

function構文使う

// 関数オブジェクトはnew演算子でインスタンスを作ることができる。
// インスタンスは、this.xxxで定義したプロパティにアクセスできる。
const Human = function(name){
  this.name = name;
  this.say = function() {
    return "My name is " + this.name;
  }
};
const human = new Human('taro');
human.say(); // -> My name is taro

// 関数オブジェクトのprototype代入したオブジェクトのプロパティは、
// 生成したインスタンス同士で"共有"されて使われる。
const prototypeObject = {
    type: 'Human',
    toString: function() {
        return this.type + ': ' + this.name;
    }
}
Human.prototype = prototypeObject;
const jiro = new Human('jiro');
jiro.toString(); // -> Human: jiro
const hanako = new Human('hanako');
hanako.toString(); // -> Human: hanako

// 共有されているので書き換えると、すべてのインスタンスに影響がある。
Human.prototype.type = 'Homo sapiens';
jiro.toString(); // -> "Homo sapiens: jiro"
hanako.toString(); // -> "Homo sapiens: hanako"

// prototypeを使ってErrorオブジェクトを継承をする
const MyError = function(msg) {
    this.message = msg || 'Exception occured';
    this.name = 'MyError';
};
MyError.prototype = new Error();
e = new MyError();
e.toString(); // -> "MyError: Exception occured"

class構文使う

classはプロトタイプベース継承の糖衣構文。ECMAScript 2015 で導入。
今まで出来ていたことを、class構文を使っても書けるようになりましたよ的なもの。

// class構文を使って関数オブジェクトを定義。
// インスタンスの作成/プロパティへのアクセスは同じ。
class HumanKlass {
  constructor(name) {
    this.name = name;
  }
  say() {
     return "My name is " + this.name;
  }
}
tom = new HumanKlass('tom');
tom.say(); // -> My name is tom

// extendsを構文を使ってErrorオブジェクトを継承
class MyErrorKlass extends Error {
  constructor(msg) {
    super();
    this.message = msg || 'Exception occured';
    this.name = 'MyError';
  }
}
ek = new MyErrorKlass();
ek.toString(); // -> "MyError: Exception occured"
MyErrorKlass.prototype // -> Errorのインスタンスが入っている。