以下のコードを書いても動くのであれ?と思いました:
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と出力される