OK, first, i'm not going to seek a method to convert the Object to String.
but i'm facing a problem like this:
String.prototype.foo = function() {
return this;
};
var rawString = "abcde";
var fooString = "abcde".foo();
console.log(typeof(rawString) + ': ', rawString);
console.log(typeof(fooString) + ': ', fooString);
or jsfiddle you preferred.
also, a screenshot is attached:
the strange thing in Javascript.
as you can see, i did almost nothing in the prototype method foo, i just return this.
but the result of typeof are totally different
Why is this? how can i just return abcde rather thant {0: "a"...} ?
Thanks!
-
1possible duplicate of Javascript WTF: a String.prototype's "this" doesn't return a string?Crescent Fresh– Crescent Fresh2012年08月18日 16:59:29 +00:00Commented Aug 18, 2012 at 16:59
-
@CrescentFresh oops, you're right. i tried to search, but i didn't make it. sorry for the duplicate question.Ya Zhuang– Ya Zhuang2012年08月18日 17:23:12 +00:00Commented Aug 18, 2012 at 17:23
1 Answer 1
The this references the String Object, so you need to return it like
return this.toString();
which in turn, creates the primitive string version and returns it.
answered Aug 18, 2012 at 17:02
jAndy
237k57 gold badges313 silver badges363 bronze badges
lang-js