9
9

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.

名前空間用のオブジェクトを作る関数

Posted at

com.example.foo.baaのような入れ子のオブジェクトを作って名前空間として活用することはよく行われるが、そのような多段入れ子のオブジェクトを一発で作る関数。これがないと面倒くさい。大抵のライブラリには入っているかもしれない。

function namespace(str) {
  var names=str.split(".")
    , i, l, cur = Function("return this")()
    ;
  for (i=0,l=names.length; i<l; i++) {
    cur[names[i]] = cur[names[i]] || {};
    cur = cur[names[i]];
  }
  return cur;
}
//使い方
namespace("com.example.foo.baa");
console.log(com); // {example: {foo: {baa: {} } } }
9
9
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
9
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?