『JavaScriptパターン』第2章 オブジェクト


オブジェクトの生成

new Object()は使わない。代わりにオブジェクトリテラルを使う。
→ コンストラクタに渡す値によって、呼び出されるコンストラクタが変わるため。

配列かどうかの検査

Array.isArray()は、引数が配列のときtrueを返す。

// Array.isArray()が未定義の場合は定義する
if (typeof Array.isArray === "undefined") {
    Array.isArray = function (arg) {
        return Object.prototype.toString.call(arg) === "[object Array]";
    }
}

var ary = [1, 2, 3];
var obj = {"key": "value"};

console.log(Array.isArray(ary)); // true
console.log(Array.isArray(obj)); // false

正規表現

エラーの投げ方

try {
    throw {
        name: "MyErrorType",
        message: "oops",
        extra: "This was rather embarrassing",
        remedy: genericErrorHandler
    };
} catch (e) {
    alert(e.message);
    e.remedy();
}