开发者

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]

This question already has answers here: Closed 11 years ago.

Possible Duplicate:

Why are there two kinds of JavaScript strings?

For example, we need to use ne开发者_JAVA技巧w 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)


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜