Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what would be the reason that any framework, or anyone, would ever need to use String/Number/Boolean object as opposed to the primitive versions? [duplicate]

Tags:

javascript

Possible Duplicate:
Why are there two kinds of JavaScript strings?

For example, we need to use new RegExp() instead of the regex literal if we need the regex expression to be dynamically calculated.

However exactly what are the edge cases when anyone will ever need to use String/Number/Boolean objects as opposed to their primitive versions ? (because I can't seem to even think of one where it will ever be needed)

like image 940
Pacerier Avatar asked Aug 09 '11 23:08

Pacerier


1 Answers

A String is an Object, but the primitive version exists which is created as a literal with 'Hello' (and is by far the most common used).

People sometimes use new String() to convert another type to a String, for example, in a function.

function leadingZero(number, padding) {
   number = new String(number);
   ...
}

Leading 0s are not significant in a Number, so it must be a String.

However, I still would have preferred to have made the Number a String by concatenating it with an empty String ('').

function leadingZero(number, padding) {
   number += '';
   ...
}

This will implicitly call the toString() of the Number, returning a String primitive.

I was reading that people say hey typeof foo==="string" is not fool-proof because if the string is created using new String the typeof will give us object.

You can make a fool proof isString() method like so...

var isString = function(str) {
   return Object.prototype.toString.call(str) == '[object String]'; 
}

jsFiddle.

This works in a multi window environment. You could also check the constructor property, but this fails in a multi window environment.

Also refer to Felix Kling's comments to this answer.

like image 182
alex Avatar answered Oct 30 '22 11:10

alex