0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Javascriptで名前空間を簡単に使う

Last updated at Posted at 2017-01-24

概要

Javascriptで名前空間を簡単につかう方法を考えてみたよ。

ヘルパー関数を作る

追記:実際つかってたら動かないことに気付いたので修正した。使用例はそのまま動くはず。

(function() {
	function splitNs(nsStr) {
		return nsStr.split(".");
	}

	function ret(nsStr) {
		function ret_helper(rt, symo) {
			if(symo.length > 0) {
				var now = symo.shift();
				if(!(Object.prototype.toString.call(rt[now]) === '[object Object]')) {
					rt[now] = {};
				}
				return ret_helper(rt[now], symo);
			} else {
				return rt;
			}
		}

		return ret_helper(window, splitNs(nsStr));
	}


	window.use = function(nsStr, self) {
		var nss = splitNs(nsStr);
		var obj = self[nss[0]];
		for(var i = 1; i < nss.length; i += 1) {
			obj = obj[nss[i]];
		}
		self[nss[nss.length - 1]] = obj;
	};

	window.ns = function(sym, fn) {
		fn.call(ret(sym));
	};
})();

使ってみる

  • 使用例
ns("a.b", function() {
	this.Cls = function() {
		function qoo() {
			console.log("qoo!");
		}

		var pub = {};
		pub.qoo = qoo;
		return pub;
	};
});
ns("a.b.c", function() {
	this.x = 1;
});

$(document).ready(function() {
	(function() {
		use("a.b.c", this);
		use("a.b.Cls", this);

		console.log("c.x", c.x);
		(new Cls()).qoo();
	})();
});
  • 出力
c.x 1
qoo!
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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?