Maintainable Javascript読んだ(Part2)

( javascript )

Programing Practice

前回の続きです。今回はPart2のメモ。 実践編です、javascript特有の癖があるのでそれを考慮した上での実装方針がわかるようだ。

Event Handling

  • アプリケーションのロジックときり分けよう!
  • Don't Pass the Event Object Around(略せなかった・・・)
    • アプリケーションロジックはイベントオブジェクトそのものに頼っては行けない
    • 処理の透過性が悪くなるし、テストしにくいんだよ! イベントオブジェクト周りを引数とかにして処理させないで!!っていういみだったのかも。

Avoid Null Comparisons

Detecting Reference Values

*どれもobjectが返るから注意

console.log(typeof {}); // "object"
console.log(typeof []); // "object"
console.log(typeof new Date()); // "object"
console.log(typeof new RegExp()); // "object"
console.log(typeof null); // "object"
  • チェックはインスタンスを見るといい
if (hoge instance Date) {
  // do something
}
if (hoge instance Error) {
  throw value;
}

Detecting Arrays

Array.isArray()ていう便利メソッドがあるけど対応しているブラウザがまだ最新なので 昔のブラウザを補完した実装がいいよね!

Separate Configration Data from Code

jsでもアプリ全体で利用する変数があると思うからそういった変数だとわかるように オブジェクトないで大文字で統一して実装するといいかも

var config = {
   PERSON_LIMIT : 2222
   TIME_LIMIT : 3333
}

if (num > config.PERSON_LIMIT) {
  // do something
}

Don't Modify Objects You Don't Own

最初から用意されているオブジェクトを変更しちゃうとまじでみんな混乱しちゃうよ! もちろん、チームで扱うこと考慮して。

rules

  • Don't override methods
  • Don't add new methods
  • Don't remove existing methods.

// bad document.getElementById = function() { return null; } なんかまちがってもこんなことしないような気がするけど、逆言うとこんなことやったらみんなが混乱しちゃうね。

Browser Detection

ブラウザの見分け方いろいろあるけど、自分のアプリケーションでどちらを優先させるかで決定の方法を柔軟に 決めていった方がいいだろうね。

User-Agent Detection

// bad
if (navigator.userAgent.indexOf("MSIE") > -1) { 
  // it is Internet Explorer
} else {
  // it is not.
}

// good
if (isInternetExplorer8OrEarlier) { 
  // it is Internet Explorer
} else {
  // it is not.
}

Feature Detection

使えるメソッドでブラウザをきり分けするっていうのもあり。この機能はこのブラウザではできないよ!って切りけするときには便利かもしれない。

if (document.getElementById) { 
  // do something
}