tags:

views:

55

answers:

1

In javascript you can call a function as a function or as a constructor. For example you can do :

myObject = new Number(13);
myPrimitiveValue = Number(13);

or simply

myPrimitiveValue = 13;

I understand the difference between the results. Can you explain me under which reasonable circumstances creating a number, a boolean or a string as an object is desirable? For example, ability to set new properties (this is something you can do on objects but can't really do on primitive values) is almost always a bad idea for objects containing number/boolean/string. Why would I want a numeric/boolean/string object?

+1  A: 

You rarely have to create objects for the basic data types.

From the Microsoft documentation of the Number object:

"The Number object is a wrapper for numeric data. The primary purposes for the Number object are to collect its properties into one object and to allow numbers to be converted into strings via the toString method. The Number object is similar to the Number data type. However, they have different properties and methods.

You rarely need to construct a Number object explicitly. The Number data type should be used in most circumstances. Since the Number object interoperates with the Number data type, all Number object methods and properties are available to a variable of type Number."

Guffa
Thank you for this, it does make sense. However it's a little bit strange, don't you think? Consider other scripting languages, for example lua, there is nothing like that in there, table (analogue of jscript object) is a table and number / string / boolean is number /string boolean. Of course it's not fair to compare very different languages, but javascript take on this IS strange. Reading ECMAScript specification I have a distinct feeling that it was written post-factum, describing some already existing implementation as is.
zespri
@zespri: Perhaps the wrappers were inspired by the similar wrappers in Java, but they are not as useful in a script language. You are right that the specification is based on an existing implementation, Javascript was announced in december 1995 and the specification was adopted in june 1997. http://en.wikipedia.org/wiki/ECMAScript
Guffa