Created
July 17, 2012 04:09
-
-
Save ashikawa/3127031 to your computer and use it in GitHub Desktop.
「美しいプログラムを書く」の添削
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
/** | |
* 美しいプログラムを書く | |
* @see http://labs.timedia.co.jp/2012/07/beautiful-code-vs-mr-oldtype.html | |
*/ | |
// $(document).ready()の短縮形。 | |
$(function () { | |
// single var pattern | |
// jQuery オブジェクトを差す変数は、先頭に「$」を付ける (その方が見やすいので) | |
// スコープを細かく分ければ、短い変数名でも衝突しない | |
var $news = $("input[name='new_version']"), | |
$olds = $("input[name='old_version']"); | |
// 本来は Html に書くべき無駄なコード | |
// 一行にまとめるより思い切って行を分けた方が理解しやすい | |
// 量が増えるようなら共通部分を関数にする | |
$news.eq(0).attr('checked', 'checked'); | |
$olds.eq(0).attr('checked', 'checked'); | |
// setup new <-> old pair | |
$news.each(function (i, element) { | |
var $old = $olds.eq(i); | |
// $(this) と同じだが、 this は避けれる時は避ける | |
$(element).data('pair', $old); | |
}); | |
// $news.each().change() ... と連結しても良いが可読性のため分割。 | |
// event 変数は使わないけれど、イベントリスナである事が明確になる | |
$news.change(function (event) { | |
// 説明用の変数 | |
var $old = $(this).data('pair'); | |
$old.attr('checked', 'checked'); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
追記 this を(条件によっては)避ける理由
http://cou929.nu/data/google_javascript_style_guide/#this