Vikas Garg
Vikas Garg

Reputation: 19

Javascript Object Prototype

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

Upvotes: 1

Views: 343

Answers (2)

Reporter
Reporter

Reputation: 3948

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.

Upvotes: 0

meouw
meouw

Reputation: 42140

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

Upvotes: 4

Related Questions