ヤマカサのプログラミング勉強日記

プログラミングに関する日記とどうでもよい雑記からなるブログです。

改訂新版JavaScript本格入門 ~モダンスタイルによる基礎から現場での応用まで その6

Chapter 5 大規模開発でも通用する書き方を身につける - オブジェクト指向構文 -

JavaScript のクラスについて学びます。

クラス

ES2015 以前では、function を使ってクラスのような構文を実現することができます。

var Employee = function(firstName, lastName) {
  this.firstName = firstName;
  this.lastName = lastName;
  this.getName = function() {
    return this.lastName + ' ' + this.firstName;
  }
};

var emp = new Employee('佐藤', '太郎');
console.log(emp.getName());

プロトタイプチェーン

継承のようなことを記述できます。

var Human = function(){};

Human.prototype = {
  hello : function() {
    console.log('hello');
  }
}

var Man = function() {
  Human.call(this);
}

Man.prototype = new Human();
Man.prototype.hi = function() {
  console.log('hi');
}

var p = new Man();
p.hello();
p.hi();

class 構文

ES2015 以降で class 構文が使えるようになりました。

class Employee {
  constructor(firstName, lastName) {
    this.firstName = firstName;
    this.lastName = lastName;
  }

  getName() {
    return this.lastName + ' ' + this.firstName;
  }
}

let p = new Employee('佐藤', '太郎');
console.log(p.getName());