有如下代码:function test_multiSingleInherit(){//测试多层单继承
//定义类Grandfather
Grandfather=function(){
this.show1=function(){
alert("Grandfather's show1");
};
};
Grandfather.prototype.ptypeField="grand";
Grandfather.prototype.ptypeFunction=function(){
alert("Grandfather's ptypeFunction");
};
//定义类Father
Father=function(){
Grandfather.call(this); //调用超类Grandfather的构造函数
this.show2=function(){
alert("Father's show2");
};
};
Father.prototype=Grandfather.prototype;
//定义类Son
Son=function(){
Father.call(this); //调用超类Father的构造函数
this.show3=function(){
alert("Son's show3");
};
};
Son.prototype=Father.prototype;
var son=new Son();
son.show1(); //调用祖父类Grandfather的方法
son.show2(); //调用父类Father的方法
son.show3(); //调用自身的方法
alert("son.ptypeField="+son.ptypeField); //调用祖父类Grandfather的原型属性
son.ptypeFunction(); //调用祖父类Grandfather的原型函数
}
问题如下:
1).如果说类Grandfather的show1方法是其成员方法,那么它的原型方法ptypeFunction又和show1有什么区别呢?
2).既然在子类中通过call函数对父类进行了初始构造,按理说就已经实现了继承关系。但据本人所查资料,发现资料中说prototype属性返回对象类型原型的引用。既然如此,那又何必使用call方法呢。但经本人多次测试,如果即想调用父类的成员方法,又想调用父类的原型方法,那么在子类中必须调用父类的call方法,也必须进行原型声明。
3).请针对上述2点进行解答!谢谢!
//定义类Grandfather
Grandfather=function(){
this.show1=function(){
alert("Grandfather's show1");
};
};
Grandfather.prototype.ptypeField="grand";
Grandfather.prototype.ptypeFunction=function(){
alert("Grandfather's ptypeFunction");
};
//定义类Father
Father=function(){
Grandfather.call(this); //调用超类Grandfather的构造函数
this.show2=function(){
alert("Father's show2");
};
};
Father.prototype=Grandfather.prototype;
//定义类Son
Son=function(){
Father.call(this); //调用超类Father的构造函数
this.show3=function(){
alert("Son's show3");
};
};
Son.prototype=Father.prototype;
var son=new Son();
son.show1(); //调用祖父类Grandfather的方法
son.show2(); //调用父类Father的方法
son.show3(); //调用自身的方法
alert("son.ptypeField="+son.ptypeField); //调用祖父类Grandfather的原型属性
son.ptypeFunction(); //调用祖父类Grandfather的原型函数
}
问题如下:
1).如果说类Grandfather的show1方法是其成员方法,那么它的原型方法ptypeFunction又和show1有什么区别呢?
2).既然在子类中通过call函数对父类进行了初始构造,按理说就已经实现了继承关系。但据本人所查资料,发现资料中说prototype属性返回对象类型原型的引用。既然如此,那又何必使用call方法呢。但经本人多次测试,如果即想调用父类的成员方法,又想调用父类的原型方法,那么在子类中必须调用父类的call方法,也必须进行原型声明。
3).请针对上述2点进行解答!谢谢!
1>show1是私有方法,ptypeFunction是提供子类共享的方法.
2>调用父类的call方法是确保子类有一个构造方法..因为修改函数的prototype属性会导致构造函数的丢失..例如..function test1(){};
//alert(typeof test1.constructor);
test1.prototype = {};
var b = new test1();
alert(typeof b.constructor.prototype.constructor);
原型方法和this方法的区别:所谓原型,即只存在一个备份,如果新建好几个Grandfather实例的话,他们都共有一个原型中的方法ptypeFunction,而同时会新建好几个show1的方法的引用。所以说如果是面向对象的js编程的话,推荐使用原型方法和原型属性。