1

I was reading Prototypes in javascript and I have written 2 small js codes which are outputting exactly same. I just want to know what is the difference between them:

Code 1:

String.sam = function() { alert('fine') };
'ok'.sam();

Code 2 with prototype:

String.prototype.sam = function() { alert('fine') };
'ok'.sam();

Please clarify the difference and the better way to use the code.

Thanks

2 Answers 2

4

Your first example doesn't work. What you are doing is creating a static method on the string object so you would have to call it statically

//OK
String.sam();
//not OK, raises error
'hello'.sam();

In your second example the keyword this will refer to the instance of the string you call it on. So you can do something like

String.prototype.sam = function() {
    console.log( this.toUpperCase() );
}

'hello'.sam(); // HELLO

This technique, although powerful is frowned upon in certain quarters. It is known as Guerrilla patching, Monkey punching or similar things. There are a few reasons it is considered bad:

  • Hard to debug (you've changed the language)
  • Easy to break other code on the page that is not aware you've altered a prototype
  • Possible clashes with future enhancements of the core.
  • Probably lots more
Sign up to request clarification or add additional context in comments.

1 Comment

Could you comment on a better alternative in your second example since you mentioned all the pitfalls involved. I am trying to wrap my head around prototypes and am curious.
0

I think, your first method adds only for this special property the alert() method. If you want create another instance, you have to do the same thing again. With protoype you define it more generally so you don't have to do the same thing again for another instance.

Perhaps http://www.javascriptkit.com/javatutors/proto.shtml will help you to understand it better.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.