JavaScript新建实例不需要带 new 的小技巧
文章目录
让我们可以不加 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 {}
耶✌️

评论
登录后参与技术讨论,分享你的经验与见解。
登录 / 注册暂无评论