ECMAscript 262 エディション 5 までは、 を使用している人がキーワードconstructor pattern
を使用するのを忘れると、大きな混乱が生じたからです。ES3 でコンストラクター関数を呼び出すときnew
に使用するのを忘れた場合、 (ブラウザーで) グローバル オブジェクトを参照し、グローバル オブジェクトを変数で上書きします。new
this
window
これはひどい振る舞いだったので、ECMA の担当者は に設定this
することにしましたundefined
。
例:
function myConstructor() {
this.a = 'foo';
this.b = 'bar';
}
myInstance = new myConstructor(); // all cool, all fine. a and b were created in a new local object
myBadInstance = myConstructor(); // oh my gosh, we just created a, and b on the window object
最後の行は、ES5 strict でエラーをスローします
"TypeError: this is undefined"
(これははるかに優れた動作です)