Help us understand the problem. What is going on with this article?

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

More than 3 years have passed since last update.
  • 勉強がてら。「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でクラスつくろうよ」と言いたかっただけ。
varmil
Typescriptを日本全土へ布教する伝道師。そう Francisco de Jasso y Azpilicueta とはわたしです。
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
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  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
ユーザーは見つかりませんでした