gpt4 book ai didi

javascript - JS中的自调用构造函数

转载 作者:行者123 更新时间:2023-11-30 12:57:24 24 4
gpt4 key购买 nike

因为我想强制执行 new,所以我创建了如下构造函数。它工作正常,即使我不使用 new 调用构造函数,实例仍然可以获得该属性。但是我很疑惑既然if语句中已经return了,为什么下面的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

最佳答案

在此代码中有两次调用Car。第一个:

var car = Car();

第二次调用的结果:

return new Car();

第二个 调用执行console.log("yeah, I can arrive here");。第一次调用永远不会运行该行。否则,您会看到两次输出。

关于javascript - JS中的自调用构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18564973/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com