-2

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?

user1895629
  • 147
  • 1
  • 1
  • 8
  • I just realized in the console theres a member: `[[PrimitiveValue]]` can I use that somehow? – user1895629 Nov 29 '13 at 01:42
  • 1
    Are you looking for [`.valueOf()`](http://es5.github.io/#x15.5.4.3)? – Bergi Nov 29 '13 at 01:45
  • 2
    What on earth are you trying to achieve? – Pointy Nov 29 '13 at 01:48
  • Maybe this answer can explain what prototype is, what it's used for, what `this` is and what it's used for and the difference between them: http://stackoverflow.com/a/16063711/1641941 If you have any questions about it please let me know. – HMR Nov 29 '13 at 03:46

1 Answers1

2

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.

Pointy
  • 405,095
  • 59
  • 585
  • 614
  • 1
    @RCV there's a difference between the primitive type `string` and the object type `String`. – Pointy Nov 29 '13 at 01:47
  • I'm aware that its pointless, as I mentioned; the question was for learning purposes and to be used in practical applications, which I dont have the time to think up for rude people – user1895629 Nov 29 '13 at 01:56
  • 2
    @user1895629 you didn't actually mention it, and this isn't a "rude" answer. It's just a factual observation. Insulting people who've taken the trouble to answer a question you've asked is a curious thing to do. – Pointy Nov 29 '13 at 02:03