Help us understand the problem. What is going on with this article?

[小ネタ]javascriptのclass constructorの戻り値はオブジェクトのとき上書きできる。

More than 1 year has passed since last update.
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 }

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

Why do not you register as a user and use Qiita more conveniently?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away