我想测试一个函数是否是一个构造函数(意味着用new
调用),或者只是一个应该按字面调用的常规函数。
这很可能是不可能的,我在这个问题上找不到任何东西,但想知道是否有可能仅仅是为了它的运动。
这是我到目前为止的基本检查:
function isConstructor(func) {
// Ensure it is a function...
if (typeof func !== 'function') {
return false;
}
// Check for at least one custom property attached to the prototype
for (var prop in func.prototype) {
if (func.prototype.hasOwnProperty(prop)) {
return true;
}
}
// No properties were found, so must not be a constructor.
return false;
}
注意:这是好奇心的问题,而不是要求。请不要说“这是一个糟糕的单元测试”或“它真的值得吗?”。这只是一个有趣的练习,看看有什么可能(尽管很糟糕/不合理/不会被使用)。
答案 0 :(得分:1)
这是不可能的,因为Javascript 中的任何函数都可以作为构造函数。您可以调用任何以new
开头的函数,使其this
指向一个新对象,就像您可以.call
使this
指向任何您想要的任何函数一样{{1}}