开发者

Javascript Object Prototype

I was reading Prototypes in javascript and I have written 2 small js codes which are outputting e开发者_高级运维xactly 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


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜