gpt4 book ai didi

javascript - 为什么 Math 是一个对象而 String 是一个函数?

转载 作者:行者123 更新时间:2023-11-30 07:23:12 25 4
gpt4 key购买 nike

以下是我的 Chrome javascript 控制台的截图:

enter image description here

为什么 Math 被认为是对象,而 StringBooleanWindow 都被认为是函数?

最佳答案

StringBoolean 是用于显式创建该类型对象的构造函数,可用作:

var s = new String("hello");
var t = new Boolean(true);

通常没有必要像这样直接使用这些构造函数,但如果出于某种原因,您需要一个完整的字符串或 bool 对象而不是原始对象,它们就在那里。


Math 是一个用作命名空间的对象,它作为一个容器来容纳一堆数学函数,例如 Math.min()Math. max(), Math.random(), 等等...它不是构造函数,不会自己创建其他对象。您可以看到 Math 对象的详细描述 here on MDN .

根据该描述:

Math is a built-in object that has properties and methods for mathematical constants and functions. Not a function object.

Unlike the other global objects, Math is not a constructor. All properties and methods of Math are static. You refer to the constant pi as Math.PI and you call the sine function as Math.sin(x), where x is the method's argument. Constants are defined with the full precision of real numbers in JavaScript.

它们是不同用途的不同东西。


Window 有点不同。它可能与宿主对象 window 相关,但尽管它报告为一个带有 native 代码的 function,但 Chrome 浏览器不允许您将其作为函数调用或作为构造函数。

关于javascript - 为什么 Math 是一个对象而 String 是一个函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30023272/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com