共计 242 个字符,预计需要花费 1 分钟才能阅读完成。
让我们可以不加 new 地新建实例.
首先, 需要使用 function
而不是class
.
function Fish() {console.log(this instanceof Fish)
}
测试一下
Fish()
>> false
<- undefined
new Fish()
>> true
<- Fish {}
所以, 可以这样
function Dog() {if (!(this instanceof Dog)) {return new Dog()
}
return this
}
试试
Dog()
<- Dog {}
new Dog()
<- Dog {}
耶✌️
正文完