大規模な開発になるほど、
共通に使われる関数なんかは役割に応じてファイルをわけて定義しますよね。
でも、共通ファイルが使う側に心地良くできてるとは限らなかったり。
function xhr(){
// Internet Explorer
if(window.ActiveXObject){
try {
return new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
return new ActiveXObject("Microsoft.XMLHTTP");
} catch (e2) {
return null
}
}
} else {
return new XMLHttpRequest();
}
}
|
pottava-common.js
おいおいおい(( ;゚Д゚))
<!DOCTYPE html>
<head><meta charset="UTF-8"></head>
<body>
<h1> Let's think about the scope!</h1>
<script type="text/javascript" src="pottava-common.js"></script>
<script type="text/javascript">
var xhr = xhr();
alert( xhr);
</script>
</body></html>
|
main.html
いやそりゃあまあ動きますけども。
関数名もよくはないけど、定義するスコープも考えて、と。
例えばこうする。
(function( win){
// return if it had been defined already.
if (win.pottava && win.pottava.common) return;
// define common object and public properties
var pottava = win.pottava || {};
pottava.common = {
xhr: _xhr,
log: _log
};
win.pottava = pottava;
// private erea
var _isdebug = true;
/**
* pottava.common.xhr
* @return XMLHttpRequest
/*
function _xhr(){
// Internet Explorer
if (window.ActiveXObject){
try {
return new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
return new ActiveXObject("Microsoft.XMLHTTP");
} catch (e2) {
return null
}
}
} else {
return new XMLHttpRequest();
}
}
/**
* pottava.common.log
* @param what you want to save as logs
/*
function _log( param){
if (_isdebug){
console.log( param);
}
}
})( window);
|
pottava-common.js
で、HTMLはこうなる。
(HTML内のスクリプトもグローバル領域にゴミが残らないようちょっと変更)
<!DOCTYPE html>
<head><meta charset="UTF-8"></head>
<body>
<h1> Let's think about the scope!</h1>
<script type="text/javascript" src="pottava-common.js"></script>
<script type="text/javascript">
(function(){
var xhr = pottava.common.xhr();
alert( xhr);
})();
</script>
</body></html>
|
main.html
ポイントは
- 定義部全体を即実行形式の無名関数で囲んで定義する。
- 共通機能はpottavaという唯一のグローバルオブジェクトの中に定義されている。
- 共通ファイルごとにpottavaオブジェクト直下のプロパティとして定義している。
こうすれば、いろんなメリットが享受できる。
- 機能追加しやすい!(公開したくない関数・変数をprivateな空間に隠蔽できる)
- 関数が役割ごとにまとまっていてコードを読みやすい
- 変数名でどきどきすることがなくなる
- グローバル領域がすっきりして名前解決が速い(ブラウザにもよるけどマイクロ秒未満ww)
amebaブログってソースコード載せるの大変なんスね...
自分なりのテンプレートつくるのに数時間使ってしまった。。