3

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,

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.

4 Answers4

4

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). This is documented here in the specification: http://www.ecma-international.org/ecma-262/5.1/#sec-15.8

The Math object can be thought of like this:

// 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. 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();
Dai
  • 141,631
  • 28
  • 261
  • 374
  • I will also add that having a `Math` constructor that creates many instances wouldn't make sense because constructors are useful when we want each instance to have its own state; like each **Person** having a unique name and address. Mathematical expressions have a specific definition (_you can't change the value of PI_) and you can't change their definitions. That's why I think the `Math` object is implemented as a singleton. Basically **Math** is _Math_ so having many **Math**s is the same thing, therefore why not have just one. – istos Nov 04 '14 at 07:55
4
typeof Math -->    "object"
typeof Date -->    "function"

Math is an Object and Date is constructor function.

new key word is used to initialize an instance with a constructor function not with objects.

Sarath
  • 9,030
  • 11
  • 51
  • 84
1

The new keyword is used when you are dealing with constructor functions. Math is a global object that has already been instantiated.

TGH
  • 38,769
  • 12
  • 102
  • 135
0

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). Math does not need to store any instance specific data, because PIdoes not change and all Math functions, like sin, cos, max etc., they always do the same thing. That's why Math exists as a static object (like a static class in other languages). 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(). You dont need to create a new Date to use this method. You call it like you would call Math.cos(x), just Date.parse('2014-11-04').

Dmitry
  • 6,716
  • 14
  • 37
  • 39