2

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!

2

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

2 Comments

great! thanks!! but feel so strange to write the "string".toString() .. LOL, odd javascript.
@bitsMix, it's an object oriented language

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.