这是一个我无法弄清楚的棘手问题。正如我从 MDN 中读到的,我们无法从 Math
创建实例。运行 new Math()
将产生异常 Math 不是构造函数
。但是 Math 在 Math.constructor 中有自己的属性。是的,它是 Object
类型,但我们可以运行它 Math.constructor()
。但即使我们通过 exec Math.constructor = Function.constructor 重新定义它,它也会抛出异常。
现在我脑子里有了一些假设:
- 构造函数包含隐藏属性,浏览器引擎拒绝调用它。
- 构造函数在浏览器引擎中解释为特殊的 C++ 对象,该对象在“TypeError:不是构造函数”集合中具有索引。
有人可以彻底回答我为什么构造函数存在但我无法创建实例吗?
提前致谢。
最佳答案
引用我自己的话,答案是
because the spec says so
The Math Object
The Math object is a single object that has some named properties, some of which are functions.
The value of the
[[Prototype]]
internal property of the Math object is the standard built-in Object prototype object (15.2.4). The value of the[[Class]]
internal property of the Math object is "Math".The Math object does not have a
[[Construct]]
internal property; it is not possible to use the Math object as a constructor with the new operator.The Math object does not have a
[[Call]]
internal property; it is not possible to invoke the Math object as a function.
javascript中的每个对象都有一个构造函数,而Math
是一个对象,因此它有一个构造函数,这并不意味着你可以创建它的新实例,它与
var Math = {
random : true,
max : false
}
new Math(); // epic fail, not a constructor (function)
关于javascript - 数学不是构造函数,但它有,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40751661/