LoginSignup
2
2

More than 5 years have passed since last update.

javascriptのクラス化

Posted at

初心者から0.1歩くらいは進んだかもしれないので記録しておく。

javascriptで関数が多くなると整理が大変になるので、クラス作成の必要性に迫られた。

その記録。

javaの様にファイルごとにクラス分けしておくと、関数名の重複などを気にする必要がなくなるので便利。

ClassSample.js

var ClassSample = (function() {

  //private変数
  var pvValue = 1;
  var pvValue2;

  //コンストラクタ
  var ClassSample = function(arg) {
    //public変数
    this.x = 5;
    this.y = 10;
    this.z = arg;
    //private変数
    pvValue2 = arg;
  };

  //クラスオブジェクト
  var cl = ClassSample.prototype;

  //public関数
  cl.f1 = function(para) {
    return para * this.x + pvValue;
  };

  //public関数
  cl.f2 = function(para) {
    return pvFunc(para);
  };

  //private関数
  var pvFunc = function(para) {
    return pvValue + para;
  };

  //戻り値
  return ClassSample;  //クラスオブジェクト
})();

main.js
function main(){

  //クラス呼び出し
  var classSample = new ClassSample(1);

  console.log("res x  " + classSample.x);
  console.log("res y  " + classSample.y);
  console.log("res z  " + classSample.z);

  console.log("res f1 " + classSample.f1(5));
  console.log("res f2 " + classSample.f2(10));

}

出力

console.log
    res x  5
    res y  10
    res z  1
    res f1 26
    res f2 11
2
2
0

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
2
2