javascript (2)

直前エントリのナニの次は AppendTo’s Screencasts とのことで Screencasts にも register して云々してみる方向。とは言えとりあえず JavaScript Quick Start Guide を終わらせよう。

JavaScript Quick Start Guide 気づき

  • !!0 とか面白い書き方
  • === な比較演算子があるのか
    • == coerces types って記述があって強制型変換って意味に変換できなかった件

デフォルト引数な考えかたはなくって

function foo(bar) {
  // Default bar to the string 'baz' if no value
  // is provided. This works because parameters
  // that are not passed to functions are undefined.
  //
  // The || operator returns the left value if it is
  // true and the right value if the left value is
  // false.
  bar = bar || 'baz';

とのこと。ええと javascript の false は boolean なナニによれば

In JavaScript, there are 6 "falsy" values (values that evaluate to false):

false, null, undefined, 0, "" (the empty string), and NaN

とのことなので、それっぽく動作するのか。
とは以下の例はちょっと納得できん。

function makeDate(year, month, day) {
  // Note that months have a zero-based index, so this
  // defaults to January 1st, 2011.
  return new Date(year || '2011', month || '0', day || '1');
}

// Now, we want to provide a month and day but default
// to a year. This will work, but is very ugly.
// Also, it requires that you remember the order of
// the arguments in the function, which might be
// hard if the function had more arguments.
makeDate(undefined, '4', '4');

出力が以下。

==> 2011-5-4 12:00:00 am

あ、_month have a zero-based index_とあるのでこれで良いのか。次に出てくるナニもなかなか凄い。

function makeDate(options) {
    return new Date(
        options.year || '2011',
        options.month || '0',
        options.day || '1');
}

// Here, we're using an object literal. It's a
// little more verbose, since we need to type the
// names of the keys, but the code is more readable,
// and we don't need to explicitly pass undefined.
makeDate({
  month: '4',
  day: '4'
});

makeDate に渡す _object literal_な記述ですが、属性の名前ベイスで大丈夫なのかどうなのか。
以下も凄いwwwww

function foo() {
  var x = 1; 
  console.log(x); //1
  if (true) { 
      var x = 2; 
      console.log(x); //2
  } 
  console.log(x); //2
}

代入式は有効だけど、宣言 (定義?) はスルーされるのか。
そして最後に closure な記述が出てきて終了。

Numbers

何コレ的アレ。

> 5/0;
==> Infinity
> typeof(NaN);
==> number
> typeof(5/0);
==> number

一応数値として評価されている模様。がしかし

> NaN == NaN
==> false

わははは的。そして最後に以下な設問。

So, how do you check if the result of an operation is NaN?

The isNaN function tells you if the argument you provide is NaN. Earlier, we learned that 5/0 is infinity but 0/0 is NaN. Verify this using isNaN on 0/0.

NaN と Infinity は違うらしい。

The isNaN function tells you if the argument you provide is NaN. Earlier, we learned that 5/0 is infinity but 0/0 is NaN. Verify this using isNaN on 0/0.

このあたりの事情は微妙というか不明ですな。次で終わりか。

Intro to Objects

javascript のオブジェクト表現は key-value-pair らしい。JSON は確かに javascript なオブジェクトなのだな。

  • 未定義な属性へのアクセスは例外ではなく undefined が戻る模様

以下なエラーチェックは今風ですな。

function sickGeometry(square) {
  var x = square && square.topLeft && square.topLeft.x;
  // ...
}

最後らへん、へろへろ状態でしたが終了。今から Screencasts に register します。

あら?

確認してみたら complete してないらしい。と思ったら RUN ボタンを click してないだけでした。