我们知道判断一个对象是否是由构造函数实例化出来的,可以用 instanceof
关键字来判断
instanceof 运算符用来测试一个对象在其原型链中是否存在一个构造函数的 prototype 属性。
所以如果直接调用一个构造函数 我们可以以此来判断它不是new
出来的对象。
function Router() {
if (!(this instanceof Router)) {
return "请使用new关键字"
}}
那如果需要直接调用,不用new 关键字的话 是否也可以实例化一个对象出来呢?当然可以!
function Router() {
if (!(this instanceof Router)) {
return new Router()
}}
好吧,就是这么简单