Javascript Best Practice自分用まとめ(1)

http://www.slideshare.net/cheilmann/javascript-best-practices-1041724

ココ読むより原文読んだ方が良いです。
あくまで自分用かつブログ記事も稼げていいんじゃね?という趣旨


■Make it understandable!

・わかりやすい命名しようよ
・駄目な例) x1 fe2 xbqnea incrementorForMainLoopWhichSpansFromTenToTwenty createNewMemberIfAgeOverTwentyOneAndMoonIsFull
・値そのものについての記述するのはやめとけ
・たとえばisOverEighteen()は他の国ではその基準は変わるかもしれないよね、isLegalAge()なら安心


■Avoid globals
・他のコードと被るから怖いよグローバル!
・回避策として、closuresとmodule patternがあるよ
例A)
// 全部グローバルなんでアクセス可能
// アクセスが閉じられていないので上書きもされる可能性があって怖いね!
var current = null;
var labels = [ ‘home’:’home’, ‘articles’:’articles’, ‘contact’:’contact’ ];
function init(){ };
function show(){
curent = 1;
};
function hide(){
show();
};

・回避策1(ただ同じモジュール名繰り返し書くのが多くなるとめんどい)
demo = {
current:null,
labels:[
‘home’:’home’,
‘articles’:’articles’,
‘contact’:’contact’
],
init:function(){
},
show:function(){
demo.current = 1;
},
hide:function(){
demo.show();
}
}

・回避策2(匿名モジュールで、グローバルなものはないよ!ただし外からアクセスする手段がほぼ無いのがたるい)
(function(){
var current = null;
var labels = [
‘home’:’home’,
‘articles’:’articles’,
‘contact’:’contact’
];
function init(){
};
function show(){
current = 1;
};
function hide(){
show();
};
})();

・回避策3(module pattern、どこがグローバルかそうでないかと設定する必要あり)
(あとモジュール名の繰り返しと、function内でsyntaxが変わるのがめどい)
module = function(){
var labels = [
‘home’:’home’,
‘articles’:’articles’,
‘contact’:’contact’
];
return {
current:null,
init:function(){
},
show:function(){
module.current = 1;
},
hide:function(){
module.show();
}
}
}();

・回避策4(Revealing Module Pattern)
(syntaxを保持しつつグローバルにできる)
module = function(){
var current = null;
var labels = [
‘home’:’home’,
‘articles’:’articles’,
‘contact’:’contact’
];
function init(){
};
function show(){
current = 1;
};
function hide(){
show();
};
return{init:init,show:show,current:current}
}();


■Stick to a strict coding style
・どのブラウザーjavascriptパーサーには非常に寛容
・でも適当なコーディングスタイルだと他の人が読むときに死ぬでしょ
・Valid Codeは良いコード
・Valid Codeはセキュアなコード
・ここであなたのコードをValidateしてください
http://www.jslint.com/



いつか続く