开发者

what is the use of prototype property in javascript? [duplicate]

开发者 https://www.devze.com 2023-03-30 08:18 出处:网络
This question already has answers here: Close开发者_如何学运维d 11 years ago. Possible Duplicate:
This question already has answers here: Close开发者_如何学运维d 11 years ago.

Possible Duplicate:

How does JavaScript .prototype work?

What is the use of prototype property when properties can be added to object even without it?

var o = {};

o.x = 5;
o.y = test;

test = new function(){ alert("hello"); };


Adding a method / property to a prototype is adding it to all objects with that prototype in their prototype chain.

Your code is adding a method/property to a single instance.

To make use of prototypes you need to create your objects using new. If you create an object via an object literal you aren't specifying the prototype for the object, as far as I know you can't set the prototype retrospectively.


You can use it to create new methods for an existing object.

String.prototype.displayFirstCharacter = function(){
   alert(this.substr(0,1));
}

"my string, first char should be 'm'".displayFirstCharacter();
0

精彩评论

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