Javascript:クラスじゃないのにthisを参照できる?

以下のコードを書いても動くのであれ?と思いました:

function getArea(width, height){
    this.width = width;
    this.height = height;
    return this.width * this.height;
}

console.log(getArea(10,20)); // 200

thisと書いていますが、これはクラスをnewしたわけではないので何を指しているんだ??? 答えはグローバルオブジェクトでした。上記の後に、

function getArea(width, height){
    this.width = width;
    this.height = height;
    return this.width * this.height;
}

console.log(getArea(10,20)); // 200

console.log(width); // 10と出力される

ことから、グローバル変数を関数から定義&初期化しているのがわかると思います。 constructorを使うと、thisの招待がもうちょっとわかります:

function getArea(width, height){
    console.log(this.constructor); // function Window() { [native code] }と出力される
    this.width = width;
    this.height = height;
    return this.width * this.height;
}

console.log(getArea(10,20)); // 200

console.log(width); // 10と出力される

こういったことを防ぐためにもuse strictをするのが良さそうです:

'use strict';

function getArea(width, height){
    console.log(this.constructor); // thisがundefinedなのでエラーになる
    this.width = width;
    this.height = height;
    return this.width * this.height;
}

console.log(getArea(10,20)); // 200

console.log(width); // 10と出力される