Last active
December 17, 2015 11:08
-
-
Save so-c/5599414 to your computer and use it in GitHub Desktop.
『JavaScriptパターン』の「5.1.1 汎用の名前空間関数」と「5.4.2 コンストラクタを構成するモジュール」
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// コンストラクタを構成するモジュール | |
MYAPP.namespace('MYAPP.utilities.Array'); | |
// 使い方 | |
// var arr = new MYAPP.utilities.Array(obj); | |
MYAPP.utilities.Array = (function () { | |
// 依存関係 | |
var upbj = MYAPP.utilities.object, | |
ulang = MYAPP.utilities.lang, | |
// プライベートのプロパティとメソッド | |
Constr; | |
// var の終わり | |
// 1回限りの初期化手続き | |
// ... | |
// パブリック API -- コンストラクタ | |
Constr = function(o) { | |
this.elements = this.toArray(o); | |
}; | |
// パブリック API -- プロトタイプ | |
Constr.prototype = { | |
constructor: MYAPP.utilities.Array, | |
version: '2.0', | |
toArray: function (obj) { | |
for(var i =0, a = [], len = obj.length; i < len; i += 1) { | |
a[i] = obj[i]; | |
} | |
return a; | |
} | |
}; | |
// 新しい名前空間に代入されたコンストラクタを返す | |
return Constr; | |
}()); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 汎用の名前空間関数 | |
var MYAPP = MYAPP || {}; | |
MYAPP.namespace = function (nsString) { | |
var parts = nsString.split('.'), | |
parent = MYAPP, | |
i; | |
if (parts[0] === 'MYAPP') { | |
parts = parts.slice(1); | |
} | |
for (i = 0; i < parts.length; i += 1) { | |
if (typeof parent[parts[i]] === 'undefined') { | |
parent[parts[i]] = {}; | |
} | |
parent = parent[parts[i]]; | |
} | |
return parent; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment