LoginSignup
18
16

More than 5 years have passed since last update.

newを省略できるコンストラクタ

Posted at

newをつけずにコンストラクタを呼んだ場合、グローバル変数を増やしてしまうことがある。

/**
 * Hogeクラス
 */
function Hoge(foo, baa) {
  this.foo = foo;
  this.baa = baa;
}

var hoge = Hoge(1,2); //newつけ忘れた!
console.log(foo, baa); //グローバル変数ができてる…

ちょっとガード節を書いておくだけで防げる。

/**
 * Hogeクラス
 */
function Hoge(foo, baa) {
  if (! (this instanceof Hoge)) { //newつけずに呼んだ際はtrue
    return new Hoge(foo, baa);
  }
  this.foo = foo;
  this.baa = baa;
}

var hoge1 = Hoge(1,2); //newをつけてないけど、問題ない
var hoge2 = new Hoge(1,2); //これでももちろん動く
18
16
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
18
16