Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
320
Help us understand the problem. What is going on with this article?
@varmil

【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でクラスつくろうよ」と言いたかっただけ。
320
Help us understand the problem. What is going on with this article?
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
varmil
Typescriptを日本全土へ布教する伝道師。そう Francisco de Jasso y Azpilicueta とはわたしです。

Comments

No comments
Sign up for free and join this conversation.
Sign Up
If you already have a Qiita account Login
320
Help us understand the problem. What is going on with this article?