最近 『JavaScript Ninja の極意』 を読んでるんだけど Java と JS の比較が出てきて面白い
JavaScript Ninjaの極意 ライブラリ開発のための知識とコーディング (Programmers’ SELECTION)
- 作者: ジョン・レシグ,John Resig,ベア・ビボー,Bear Bibeault,勝亦勇,吉川邦夫
- 出版社/メーカー: 翔泳社
- 発売日: 2013/05/25
- メディア: 大型本
- この商品を含むブログ (2件) を見る
最近 『JavaScript Ninja の極意』 (の原著 『Secrets of the JavaScript Ninja』) を読んでるんだけど、なんかいちいち Java と JavaScript を比較してて面白い。
JavaScript の関数が第一級のオブジェクトで、コールバック関数として使用可能である、みたいなことを説く章では配列のソートの例が出ていて、以下のような Java のコードと JavaScript のコードが比較されていた。
Arrays.sort(values, new Comparator<Integer>() { public int compare(Integer value1, Integer value2) { return value2 - value1; } });The
compare()
method of the inlineComparator
implementation is expected to return a negative number if the ... (略) ...The wordiness of this approach becomes even more apparent when we consider the equivalent JavaScript code that takes advantage of JavaScript's functional capabilities:
var values = [ 213, 16, 2058, 54, 10, 1965, 57, 9 ]; values.sort(function (value1, value2) { return value2 - value1; });No interfaces. No extra object. One line. We simply declare an inline anonymous function that we directly pass to the
sort()
method of the array.
という感じ。 JavaScript の本で Java と比較してるの見たことないからなんか新鮮だなーって思った。
Java の例を出す前にわざわざ次のような断りを入れてるのも面白かった。
A novice Java developer might create a concrete class that implements this interface, but to make a fair comparison, we're going to assume a fair level of Java savvy-ness and use an inline anonymous implementation.
Java 初心者が無名内部クラスを知らずにいちいちクラス定義しちゃうのとかあるあるだよなー。 Java 8 が来たら Java の例が Lambda 式を使うものに変わるのだろうか。