LoginSignup
0
0

More than 3 years have passed since last update.

javascriptの共通処理を作成(共通処理用のオブジェクトから各オブジェクトにmethodをコピーして利用する)

Last updated at Posted at 2021-05-22

javascriptで共通処理を作成する際に少しクラスっぽく作成。
※「$(function () {})」はjqueryになります。

■ html

sample.js → test.js の順に読み込む必要があります。

index.html
<script src="sample.js"></script>
<script src="test.js"></script>

■ sample.js

共通処理を記載します

sample.js
// Sampleオブジェクトを上書きしないように作成します。
Sample = function () { return typeof Sample === 'undefined' ? {} : Sample; };

$(function () {
  /**
   * SampleにCommonとして設定する
   *
   * @constructor
   */
  Sample.Common = function () {
    const self = this;
    self.setup();
  };
  /**
   * 設定メソッド
   */
  Sample.Common.prototype.setup = function () {
    const self = this;

    self.xxx = {};
    self.xxx.yyy = 80;
  };
  /**
   * ベースのメソッド1
   *
   * @param {int} value 対象データ
   * @returns {int} 
   */
  Sample.Common.prototype.method1 = function (value) {
    return value;
  };
  /**
   * ベースのメソッド2
   *
   * @param {int} value 対象データ
   * @returns {int} 
   */
  Sample.Common.prototype.method2 = function (value) {
    return value;
  };
});

■ test.js

共通処理を使用する側のjsになります

test.js
// Sampleオブジェクトを上書きしないように作成します。
Sample = function () { return typeof Sample === 'undefined' ? {} : Sample; };

$(function () {
  /**
   * SampleにTestとして設定する
   *
   * @constructor
   */
  Sample.Test = function () {
    const self = this;
    // Sample.Commonの初期設定を呼び出します
    self.setup();
  };
  // Sample.Commonの処理をSample.Testに反映します
  Sample.Test.prototype = Object.create(Sample.Common.prototype);

  // オブジェクトを生成します
  const obj = new Sample.Test();
  // Sample.Commonで定義している処理が利用できます
  const result= obj.method1(111);
});
0
0
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
0
0