In javascript, what is the difference in applying a toString() method to the primitive datatype, number like this
var myString = myNumber.toString();
and applying the same toString() method by creating a reference datatype equivalent, the Number class like this
var numberObject = new Number(myNumber);
var myString = numberObject.toString();
-
1The primitive is converted temporarily into an object to call the method, then the object is goneEsailija– Esailija2012年11月11日 12:40:14 +00:00Commented Nov 11, 2012 at 12:40
2 Answers 2
In a chrome console if you type:
new Number(10).toString === (10).toString
It returns true, so I suppose there is no difference between the two since both functions refers to the same reference.
Both are equivalent and give the same result.
JavaScript allows to create objects without using new
keyword.
For example, you may create an array using new Array(1, 2, 3)
, but you may also use the shorter syntax [1, 2, 3]
.
Use shorter notations ((123).toString()
, "hello ".trim()
, [1, 2, 3].reverse()
, etc.) whenever possible. They are explicit enough, so there is no need to pass by a verbose new <Type>()
notation.
-
i know that both of them give the same result but when and why should i prefer one method over the other?user1463541– user14635412012年11月11日 12:15:14 +00:00Commented Nov 11, 2012 at 12:15
-
@user1463541: use shorter notations (
(123).toString()
,"hello ".trim()
,[1, 2, 3].reverse()
, etc.) whenever possible. They are explicit enough, so there is no need to pass by anew <Type>()
notation.Arseni Mourzenko– Arseni Mourzenko2012年11月11日 13:37:13 +00:00Commented Nov 11, 2012 at 13:37