1

newを強制したいので、以下のようにコンストラクタを作成します。newでコンストラクターを呼び出さなくても、インスタンスは引き続きプロパティを取得できます。しかし、if ステートメントでは既に が返されているため、以下のステートメントを if ステートメントで呼び出すことができるのはなぜでしょうか?

function Car(){
    if(!(this instanceof Car)){
        return new Car();
        console.log("can i arrive here?");
    }
    this.tires = "I have four tires";
    console.log("yeah,I can arrive here");
}

//Note: without new
var car = Car();//output=> yeah,I can arrive here
console.log(car.tires);//output => I have four tires
4

3 に答える 3