JavaScript 第6版 例9-2
いまさらながらオライリーの「JavaScript 第6版」を読んでいるのだけど、219 ページに書かれていプログラムを動かしてみたところ、本に書いてあるとおりの結果がブラウザコンソールに表示されなかった。いろいろ探したり試したりして答えを見つけたので、動いたプログラムをあげてみる。
<!DOCTYPE html> <html> <head> <title>Test</title> <script src="js/range.js"></script> <meta http-equiv="content-type" content="text/html; charset=utf-8" /> <meta http-equiv="content-script-type" content="text/javascript" /> <meta http-equiv="content-style-type" content="text/css" /> </head> <body> <script> var r = new Range(1, 3); console.log(r.includes(2)); r.foreach(console.info.bind(console)); console.log(r + ""); </script> </body> </html>
function Range(from, to) { this.from = from; this.to = to; } Range.prototype.includes = function(x) { return this.from <= x && x <= this.to; } Range.prototype.foreach = function(f) { for (var x = Math.ceil(this.from); x <= this.to; x++) { f(x); } } Range.prototype.toString = function() { return "(" + this.from + "..." + this.to + ")"; }
オリジナルから変更したのは foreach の呼び出し方と、最後の r だけ console.log に渡しているところ。前者はオリジナルのまま実行すると、Firefox で TypeError が発生したため。後者は、Firefox では toString が呼び出されなかったため。
前者について、以下を参考にした。
後者について、toString は文字列が期待されるときに自動的に呼び出されるようなので、空文字と結合してみた。このやり方はなんだか邪道な感じもする。素直に toString 呼び出せばいいよね。