,

Javascript作法

  • コメントをつける

 すべてのメソッド
 わかりにくいコード
間違っていそうなコード

  • 名前

 論理的な名前を長さを気にせず付ける
 変数には名詞を
 関数は動詞で始める
 fooとかtempは避ける

×


  • -

document.getElementById("some").onclick = doSomething;
×
element.innerHTML="

";

var child_element = document.createElement("div");
child_element.class = "popup2;
element.addChild(child_element);
×
.foo{ width:expression(document.offsetWidth+"px"); }
element.style.color="red";
element.style.cssText="background:blue;border:1pxsolidred";

×
//thewrongway!!!
function handleClick(event){
var popup=document.getElementById("popup");
popup.style.left=event.clientX+"px";
popup.style.top=event.clientY+"px";
popup.className="reveal";
}

//win!!
function handleClick(event){
showPopup(event.clientX,event.clientY);
}
function showPopup(x,y){
var popup=document.getElementById("popup");
popup.style.left=x+"px";
popup.style.top=y+"px";
popup.className="reveal";
}

  • 自分で作っていないオブジェクトは変更しない

//don't add new methods
Array.prototype.awYeah=function(){
alert("Awyeah!");
};
//don't override methods
YUI.use=function(){
alert("Awyeah!");
};

  • グローバル関数を避ける

var Controller={
 handleClick:function(event){
  this.showPopup(event.clientX,event.clientY);
 },
 showPopup:function(x,y){
  var popup=document.getElementById("popup");
  popup.style.left=x+"px";
  popup.style.top=y+"px";
  popup.className="reveal";
 }
};

  • エラーを自分で作る

var Controller={
addClass:function(element,className){
if(!element){
thrownewError("addClass:1stargumentmissing.");
}
element.className+=""+className;
}
};

  • nullとの比較を避ける

×
items != null

items instanceof Array

  • 設定データの分離

 URL
 表示する文字列
 Javascriptで生成するHTML
 設定(一ページあたりのアイテム数)
 繰り返し使われる特有の値
 将来的に変更される可能性のあるあらゆる変数
×
function validate(value){
 if(!value){
  alert("Invalidvalue");
  location.href="/errors/invalid.php";
 }
}

var config={
 urls:{
  invalid:"/errors/invalid.php"
 },
 strs:{
  invalidmsg:"Invalidvalue"
 }
};
function validate(value){
 if(!value){
  alert(config.strs.invalidmsg);
  location.href=config.urls.invalid;
 }
}

  • 一オブジェクト一ファイル、antなどでminify,ドキュメント作成も自動で

当たり前だけどめんどくさい時もあるんですよね