329
314

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 2014-11-17
  • 勉強がてら。「TypeScript使えばいいじゃん」「ES6」とか言わないで。

hogeクラスをつくるとき

1. 一般的なつくりかた

// constructor
var hoge = function(arg) {
  this.x = 5;
  this.y = 10;
  this.z = arg;
};

// メソッド
hoge.prototype = {
  f1: function() {
    return true;
  },
  f2: function() {
    return false;
  }
};

var instance = new hoge(1);
// hoge {x: 5, y: 10, z: 1, f1: function, f2: function}

2. グレートなつくりかた

var hoge = (function() {

  var FOOFOO = 777; // クラス内定数

  // constructor
  var hoge = function(arg) {
    this.x = 5;
    this.y = 10;
    this.z = arg;
  };

  var p = hoge.prototype;

  p.f1 = function() {
    return true;
  };

  p.f2 = function() {
    return false;
  };

  return hoge;
})();

var instance = new hoge(1);
// hoge {x: 5, y: 10, z: 1, f1: function, f2: function}

所感

  • 個人的には1よりも2の方がまとまっていて好きです。
  • 「2でクラスつくろうよ」と言いたかっただけ。
329
314
1

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
329
314

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?