0
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のclass constructorの戻り値はオブジェクトのとき上書きできる。

0
Posted at
index.js
class Test{
    constructor(){
        this.a = 12;
        return {
            a: 5
        };
    }
}
class Test2{
    constructor(){
        this.a = 12;
        return true;
    }
}
const test = new Test();
console.log(test.a); // 5

const test = new Test2();
console.log(test); // Test2 { a: 12 }

この挙動は仕様ではある。
が、少なくとも直感的ではない。
ただしこの挙動はコンストラクタ関数の挙動と全く同じだったりするので、構文糖という意味では一貫性を持っている。
・・・個人的には何かしらのエラー発してほしかった。それだけ。

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