319
Help us understand the problem. What are the problem?

More than 5 years have passed since last update.

posted at

updated at

【javascript】やさしいクラスの作り方

  • 勉強がてら。「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でクラスつくろうよ」と言いたかっただけ。
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Sign upLogin
319
Help us understand the problem. What are the problem?