这个题还是有点懵的,网上没什么答案,看了别人的回答感觉不是很行,就自己想了,我们可以使用原型链上的一个属性来记录次数,同时还需要判定是否是new调用
let cl = function (name) {
this.name = name
if (this instanceof cl) {//判定是否是new调用
if (cl.prototype.count !== undefined) {
cl.prototype.count++
}
else {
cl.prototype.count = 0
}
}
this.count = cl.prototype.count
}
console.log(new cl(1))//{"name":1,"count":0}
cl()
console.log(new cl(2))//{"name":2,"count":1}