我以一种奇怪的方式使用 eval
函数,作为构造函数。
try {
var y = new eval()
} catch(error) {
console.log("caught a " + error.name + ": " + error.message);
}
它抛出错误,
caught a TypeError: function eval() { [native code] } is not a constructor
如错误消息所示,eval 是一个函数而不是构造函数。
问题是,不是所有的 javascript 函数都充当构造函数吗?
最佳答案
并非所有函数都是构造函数。
构造函数是 function values with a [[Construct]] internal property ,并非所有功能都有。这在 6.1.7.2 Object Internal Methods and Internal Slots 中有明确说明。语言规范:
A function object is not necessarily a constructor and such non-constructor function objects do not have a [[Construct]] internal method.
使用 new
或 Reflect.construct
调用非构造函数作为构造函数会抛出 TypeError
。
关于javascript - 不是所有的 JavaScript 函数都是构造函数吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34092403/