コンストラクタ関数内では return する変数の型によって返るモノが変わる
JavaScript で、(便宜上の)コンストラクタ関数を new
で呼ぶ時、関数内の途中で return
があると、その値が帰ると思っていた。これは半分は正しいのだが、半分は間違っていた。
たとえば以下は undefined
になるんで正しい。
var Hoge; Hoge = function () { this.aaa = 'hoge'; return {}; }; console.log(new Hoge().aaa); // undefined Hoge = function () { this.aaa = 'hoge'; return function () {}; }; console.log(new Hoge().aaa); // undefined
ところが以下は、コンストラクタ内での this
に当たるものがそのまま返されている。 Chrome で確認。
Hoge = function () { this.aaa = 'hoge'; return true; }; console.log(new Hoge().aaa); // hoge Hoge = function () { this.aaa = 'hoge'; return 1; }; console.log(new Hoge().aaa); // hoge Hoge = function () { this.aaa = 'hoge'; return 'aaa'; }; console.log(new Hoge().aaa); // hoge Hoge = function () { this.aaa = 'hoge'; return null; }; console.log(new Hoge().aaa); // hoge Hoge = function () { this.aaa = 'hoge'; return undefined; }; console.log(new Hoge().aaa); // hoge
どうやら、コンストラクタ内で作ったオブジェクトを return
した時にのみ、それが new
した元に返る模様。つまり new
すれば返り値はオブジェクトであると保証されているということか。
基本の基なのかもしれないけど、知らなかったのでメモった。