在JavaScript中,prototype对象是实现面向对象的一个重要机制。所有function类型的对象都有一个prototype的属性。prototype提供了一个共享属性和方法的机制。以下这个例子仅仅展示了prototype是如何让不同对象共享这个SayHello函数的。

 
  
  1.  function Person(name)  
  2.     {  
  3.     this.name = name;   //设置对象属性,每个对象各自一份属性数据  
  4.     };  
  5.       
  6.     Person.prototype.SayHello = function() 
  7. //给Person函数的prototype添加SayHello 方法。  
  8.     {  
  9.         alert("Hello, I'm " + this.name);  
  10.     }  
  11.   
  12.  var BillGates = new Person("Bill Gates");//创建BillGates 对象  
  13.  var SteveJobs = new Person("Steve Jobs");   //创建 SteveJobs 对象  
  14.   
  15. BillGates.SayHello();//通过 BillGates 对象直接调用到 SayHello 方法  
  16. SteveJobs.SayHello(); //通过 SteveJobs 对象直接调用到 SayHello 方法  
  17. alert(BillGates.SayHello == SteveJobs.SayHello); 
  18.  //因为两个对象是共享 prototype的 SayHello,所以显示:true  
prototyp既然能够任意的添加新的方法和属性,那么我们也可以为JavaScript内置的一些Object通过prototype
的方式去覆盖或者重写已有的方法。

而很多牛人也正是这么做的,举一个例子:
我们来看一段摘自MicrosoftAjax.debug.js中的代码:
 
  
  1. String.prototype.trim = function String$trim() {  
  2.     if (arguments.length !== 0) throw Error.parameterCount();  
  3.     return this.replace(/^\s+|\s+$/g, '');  
这个拓展String对象中的trim方法。方便开发者对string进行trim的操作。