在JavaScript中,prototype对象是实现的一个重要机制。所有function类型的对象都有一个prototype的属性。prototype提供了一个共享属性和方法的机制。以下这个例子仅仅展示了prototype是如何让不同对象共享这个SayHello函数的。
- function Person(name)
- {
- this.name = name; //设置对象属性,每个对象各自一份属性数据
- };
- Person.prototype.SayHello = function()
- //给Person函数的prototype添加SayHello 方法。
- {
- alert("Hello, I'm " + this.name);
- }
- var BillGates = new Person("Bill Gates");//创建BillGates 对象
- var SteveJobs = new Person("Steve Jobs"); //创建 SteveJobs 对象
- BillGates.SayHello();//通过 BillGates 对象直接调用到 SayHello 方法
- SteveJobs.SayHello(); //通过 SteveJobs 对象直接调用到 SayHello 方法
- alert(BillGates.SayHello == SteveJobs.SayHello);
- //因为两个对象是共享 prototype的 SayHello,所以显示:true
prototyp既然能够任意的添加新的方法和属性,那么我们也可以为JavaScript内置的一些Object通过prototype的方式去覆盖或者重写已有的方法。而很多牛人也正是这么做的,举一个例子:我们来看一段摘自MicrosoftAjax.debug.js中的代码:
- String.prototype.trim = function String$trim() {
- if (arguments.length !== 0) throw Error.parameterCount();
- return this.replace(/^\s+|\s+$/g, '');
- }
这个拓展String对象中的trim方法。方便开发者对string进行trim的操作。