[英]Why Math Object does not need new keyword in javascript
I have know that Math
is an Object in javascript, however in the book it says when use the Math Object, we do not need to use the new keyword.For example, 我知道
Math
是javascript中的一个Object,但是在书中它说当使用Math Object时,我们不需要使用new关键字。例如,
var pi = Math.PI;
alert(pi);
I want to know why it does not need, and in other Object, like Date
, it needs the new keyword. 我想知道它为什么不需要,而在其他Object中,比如
Date
,它需要new关键字。
Math
is actually the name of a property of the implicit global
object in ECMAScript, which is a plain-old Javascript object, of type Math
(defined by giving it properties to this single instance, similar to how JSON works). Math
实际上是ECMAScript中隐式global
对象的属性的名称,ECMAScript是一个普通的Javascript对象,类型为Math
(通过为此单个实例提供属性来定义,类似于JSON的工作方式)。 This is documented here in the specification: http://www.ecma-international.org/ecma-262/5.1/#sec-15.8 这在说明书中记录: http : //www.ecma-international.org/ecma-262/5.1/#sec-15.8
The Math
object can be thought of like this: Math
对象可以这样想:
// within the "global" context:
var Math = {
PI: 3.14,
sin: function(x) { ... },
cos: function(x) { ... }
};
Note that no constructor function is defined (nor is Call
defined either), so the expression new Math()
is meaningless and undefined. 请注意,没有定义构造函数(也没有定义
Call
),因此表达式new Math()
没有意义且未定义。 If it was, then it would look like this: 如果是,那么它看起来像这样:
function Math() {
this.PI = 3.14;
this.sin = function(x) { ... };
this.cos = function(x) { ... };
};
var Math = new Math();
typeof Math --> "object"
typeof Date --> "function"
Math is an Object and Date is constructor function. Math是Object,Date是构造函数。
new
key word is used to initialize an instance with a constructor function not with objects. new
关键字用于使用不包含对象的构造函数初始化实例。
The new keyword is used when you are dealing with constructor functions. 在处理构造函数时使用new关键字。 Math is a global object that has already been instantiated.
Math是一个已经实例化的全局对象。
When you call a new Date([optional parameter])
you create a new instance of the Date
function which stores data specific to this instance (date and time). 当您调用
new Date([optional parameter])
您将创建Date
函数的新实例,该实例存储特定于此实例的数据(日期和时间)。 Math
does not need to store any instance specific data, because PI
does not change and all Math
functions, like sin
, cos
, max
etc., they always do the same thing. Math
不需要存储任何特定于实例的数据,因为PI
不会改变,所有Math
函数,如sin
, cos
, max
等,它们总是做同样的事情。 That's why Math
exists as a static object (like a static class in other languages). 这就是
Math
作为静态对象存在的原因(就像其他语言中的静态类一样)。 There is no need to create new instances of this object, you can use the same instance everywhere. 无需创建此对象的新实例,您可以在任何地方使用相同的实例。 BTW
Date
has static methods too, like Date.parse()
. BTW
Date
也有静态方法,比如Date.parse()
。 You dont need to create a new Date
to use this method. 您无需创建新
Date
即可使用此方法。 You call it like you would call Math.cos(x)
, just Date.parse('2014-11-04')
. 你称之为
Math.cos(x)
,就像Date.parse('2014-11-04')
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.