0
1

More than 3 years have passed since last update.

constっぽい処理。

Last updated at Posted at 2019-11-14

先日やたらレガシーな案件で、スポットのお手伝いとしてJSを書きました。
その時constの代わりが欲しくなって変わりの処理を書いたので一応メモ書き。

/** GlobalRegistor CLASS */ (function () {

  "use strict";

  // constructor

  function GlobalRegistor () {}

  // static accessor

  Object.defineProperty(GlobalRegistor, 'global', {
      /**
       * @return {Object} global object
       */
      get: function() {
          return new Function('return this')();
      }
  });

  // static

  Object.defineProperty(GlobalRegistor, 'readOnly', { writable: false,
      /**
       * @param  {String} name
       * @param  {Any}    value
       * @return {Void}
       */
      value: (function readOnly (name, value) {
          if (GlobalRegistor.global[name] === void 0) {
              Object.defineProperty(GlobalRegistor.global, name, { writable: false, value: value });
          } else {
              throw new Error(name + ' is Declare Property');
          }
      })
  });

  GlobalRegistor.readOnly('GlobalRegistor', GlobalRegistor);

})();

使い方

 .js
GlobalRegistor.readOnly('globalModules', {});
window.globalModules.fn  = function () { console.log('success!'); };
window.globalModules     = null;
window.globalModules.fn(); // success!
widnow.globalModules.foo = 1;
widnow.globalModules.foo = 2;
console.log(widnow.globalModules.foo); // 2

GlobalRegistor.readOnly('foo', 1);
console.log(widnow.foo); // 1
widnow.foo = 999;
console.log(widnow.foo); // 1
GlobalRegistor.readOnly('foo', 999); // error
0
1
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
1