what is the use of prototype property in javascript?

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.


您可以使用它为现有对象创建新方法。

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

"my string, first char should be 'm'".displayFirstCharacter();
链接地址: http://www.djcxy.com/p/30070.html

上一篇: 如何制作一个功能去追逐元素

下一篇: 在JavaScript中使用prototype属性有什么用?