在js中,每个对象都有一个prototype属性:返回对象类型原型的引用。很拗口!习语“依葫芦画瓢”,这里的葫芦就是原型,那么“瓢.prototype” 返回的就是葫芦,或者“瓢.prototype= new 葫芦()”。 prototype的用途: 继承 有一个对象--子类: function 子类() { this.lastname = "Samuel"; } 有一个对象--父类: function 父类() { this.firstname = "Shen"; } 现在子类是有名无姓,父类是有姓无名,如果子类要有名有姓的话,只要说明--子类的原型是父类--就可以了,即子类继承自父类: 子类.prototype = new 父类(); 至此,子类就不再是有名无姓了。 alert(子类.firstname + " " + 子类.lastname); //Samuel Shen 牵一发而动全身 既然prototype返回的是原型的引用,那么如果改变原型的话,所有继承自该原型的对象都将受到影响。 function Point(x,y) { this.x = x; this.y = y; } var p1 = new Point(1,2); var p2 = new Point(3,4); Point.prototype.z = 0; //动态为Point的原型添加了属性 alert(p1.z); //0 alert(p2.z); //0 /***************************************************************************/ function Person(name,sex) { //Person类的构造函数 this.name = name; this.sex = sex; } Person.prototype.age = 12; //为Person类的prototype属性对应的prototype对象的属性赋值, //相当于为Person类的父类添加属性 Person.prototype.print = function() { //为Person类的父类添加方法 alert(this.name+"_"+this.sex+"_"+this.age); }; var p1 = new Person("name1","male"); //p1的age属性继承子Person类的父类(即prototype对象) var p2 = new Person("name2","male"); p1.print(); //name1_male_12 p2.print(); //name2_male_12 p1.age = 34; //改变p1实例的age属性 p1属性在不指向Person的prototype属性 p1.print(); //name1_male_34 p2.print(); //name2_male_12 Person.prototype.age = 22; //改变Person类的超类的age属性 p1.print(); //name1_male_34(p1的age属性并没有随着prototype属性的改变而改变) p2.print(); //name2_male_22(p2的age属性发生了改变) p1.print = function() { //改变p1对象的print方法 alert("i am p1"); } p1.print(); //i am p1(p1的方法发生了改变) p2.print(); //name2_male_22(p2的方法并没有改变) Person.prototype.print = function() { //改变Person超类的print方法 alert("new print method!"); } p1.print(); //i am p1(p1的print方法仍旧是自己的方法) p2.print(); //new print method!(p2的print方法随着超类方法的改变而改变)