构造函数中
this
指向new
创建的实例。所以可以通过在函数内判断this
是否为当前函数的实例进而判断当前函数是否作为构造函数。
function F(){
if(this instanceof F){
console.log('我现在是作为构造函数')
}
else {
console.log('我现在是普通函数')
}
}
F(); // 我现在是普通函数
new F(); // 我现在是作为构造函数
构造函数中
this
指向new
创建的实例。所以可以通过在函数内判断this
是否为当前函数的实例进而判断当前函数是否作为构造函数。
function F(){
if(this instanceof F){
console.log('我现在是作为构造函数')
}
else {
console.log('我现在是普通函数')
}
}
F(); // 我现在是普通函数
new F(); // 我现在是作为构造函数