一、原型链:利用原型让一个引用类型继承另一个引用类型的属性和方法
每个构造函数都有一个原型对象,原型对象都包含一个指向构造函数的指针,而实例都包含一个指向原型对象的内部指针。
实现原性链的基本模式:
function supertype(){ this.colors =[“red”, “blue”, “green”];}function subtype(){}subtype.prototype = new supertype();var instance1 = new subtype();instance1.colors.push(“black”);alert(instance1.colors); //red, blue, green, blackvar instance2 = new subtype();alert(instance2.colors); //red, blue, green, black
最后的结果:intance指向subtype的原型,而subtype的原型又指向supertype的原型,supertype继承了object
所有函数的默认原型都是object的实例
问题:会产生引用类型值的问题
比如,创建了一个子类的实例,如果对子类实例的属性进行了修改,那么创建其他子类的时候都会收到影响,代码如下:
function supertype(){ this.colors =[“red”, “blue”, “green”];}function subtype(){}subtype.prototype = new supertype();var instance1 = new subtype();instance1.colors.push(“black”);alert(instance1.colors); //red, blue, green, blackvar instance2 = new subtype();alert(instance2.colors); //red, blue, green, black
以上结果说明会影响其他实例的属性值
二、借用构造函数:在子类型构造函数的内部调用超类型构造函数
function supertype(){ this.colors =[“red”, “blue”, “green”];}function subtype{}( supertype.call(this); //继承了supertype。通过调用supertype的构造函数,借用其构造结构}var instance1 = new subtype();instance1.colors.push(“black”);alert(intance1.colors); //red,blue,green,blackvar instance2 = new subtype();alert(instance2.colors); //red,blue,green
使用该方法可以在子类构造函数中向超类型构造函数传递参数,如下:
function supertype(name){ this.name = name;}function subtype(){supertype.call(this,“nicholas”); //传入参数,利用这个参数初始化父类构造函数中的namethis.age = 29;}var instance = new subtype();alert(instance.name); //nicholasalert(instance.age); //29
问题:不方便复用
三、组合式继承:使用原型链实现对原型属性和方法的继承,而通过借用构造函数来实现对实例属性的继承
示例代码:
function supertype(name){this.name = name;this.colors = [“red”, “blue”,“green”];}supertype.prototype.sayname = function(){ //定义了一个方法,该方法在继承的子类中也可以用 alert(this.name);}function subtype(name, age){supertype.call(this, name); //继承supertype的一部分,this指subtype,this.age = age; //自己新定义的属性age也可以进行赋值}subtype.prototype = new supertype(); //利用原型继承,可以使用父类的方法(见原型链继承)subtype.prototype.sayage = function(){ //定义subtype特有的新方法 alert(this.age);}var instance1 = new subtype(“martin”, 10);instance1.colors.push(“black”);alert(instance1.colors); //red,blue,green,blackinstance1.sayname(); //martininstance1.sayage(); //10var instance2 = new subtype(“greg”, 27);alert(instance2.colors); //red,blue,greeninstance2.sayname(); //greginstance2.sayage(); //27
相关推荐:
js中的继承方式实例详解
js实现继承的几种方式
以上就是js的继承方法--案例说明的详细内容。
