javascript - 数学不是构造函数,但它有

标签 javascript constructor

这是一个我无法弄清楚的棘手问题。正如我从 MDN 中读到的,我们无法从 Math 创建实例。运行 new Math() 将产生异常 Math 不是构造函数。但是 Math 在 Math.constructor 中有自己的属性。是的,它是 Object 类型,但我们可以运行它 Math.constructor()。但即使我们通过 exec Math.constructor = Function.constructor 重新定义它,它也会抛出异常。

现在我脑子里有了一些假设:

  • 构造函数包含隐藏属性,浏览器引擎拒绝调用它。
  • 构造函数在浏览器引擎中解释为特殊的 C++ 对象,该对象在“TypeError:不是构造函数”集合中具有索引。

有人可以彻底回答我为什么构造函数存在但我无法创建实例吗?

提前致谢。

最佳答案

引用我自己的话,答案是

because the spec says so

spec says

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/

相关文章:

javascript - 将多个 div 拖入另一个 jQuery

javascript - D3 Zoom 无法读取未定义的属性 'transform'

javascript - 为什么 asp 隐藏字段没有从客户端设置?

javascript - 链表替换和删除

javascript - 是否可以测试 javascript 函数是否是构造函数?

javascript - jQuery UI Datepicker,从一个日历移动到下一个日历?

java - 我可以在其构造函数中引用一个对象吗?

android - 防止 Proguard 删除 fragment 的空构造函数

c++ 构造函数和初始化程序行为。这5个代码有什么区别?

c++ - 在另一个类的构造函数中创建 n 个对象的最佳方法?