3
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Javascriptでnew 演算子でも普通の関数としても呼び出せるコンストラクタの作り方

Last updated at Posted at 2019-08-21

JavascriptのちょっとしたHackyなコードです。
Person(name, age)でも呼べるし new Person(name, age)とも呼べるような関数の作成方法です。

コード

function Person(name, age) {
  if(!(this instanceof Person)) return new Person(name, age);
  this.name = name
  this.age = age
}

考え方

コンストラクタとして呼び出されたら普通に処理。
関数として呼び出されたらコンストラクタ呼び出しとして呼びだし直す。

3
0
6

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
3
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?