Getting a strings value from string.prototype javascript

90 views Asked by At

Hi so I'm trying to learn a little more about prototyping and javascript and so lets say I have this code

String.prototype.getVal=function() 
{
    return ?
};

How would a string so that 'Spencer'.getVal()==='Spencer' would I have to use this within the function and then iterate over each character in the object?

1

There are 1 answers

3
Pointy On

This is pointless but

String.prototype.getVal = function() { return this.toString(); };

It's pointless because you can just use .toString() directly.

alert( new String("pointless").toString() === "pointless" ); // true

or

alert( String( new String("pointless") ) === "pointless" ); // also true

The String constructor, when invoked without new, basically returns the .toString() value of its argument if it's an object.