Js面向对象程序设计——继承(组合继承)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zhaostrong/article/details/86155569

Js面向对象程序设计——继承(组合继承)

  • 示例:
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);
	this.age=age;
}
//继承方法
SubType.prototype=new SuperType();
SubType.prototype.sayAge=function(){
	alert(this.age);
};

var instance1=new SubType("Nicholas",29);
instance1.colors.push("black");
alert(instance1.colors);  //"red,blue,green,black"
instance1.sayName();  //"Nicholas";
instance1.sayAge();  //29

var instance2=new SubType("Greg",27);
alert(instance2.colors); // "red,blue,green"
instance2.sayName();  //Greg
instance2.sayAge();  //27
  • 在这个例子中,superType构造函数定义了俩个属性:name和colors.SuperType的原型定义了一个方法sayName()。SubType构造函数在调用superType构造函数时传入了name参数,紧接着又定义了它自己的属性age。然后,将SuperType的实例赋值给SubType的原型,然后又在该新原型上定义了方法sayAge()。这样一来,就可以让俩个不同的SubType实例既分别拥有自己属性——包括colors属性,又可以使用相同的方法了。
  • 组合继承避免了原型链和借用构造函数的缺陷,融合了它们的优点,成为JavaScript中最常用的继承模式。而且,instanceof和isPrototypeOf()也能够用于识别基于组合继承创建的对象。

参考了Javascript高级程序设计

猜你喜欢

转载自blog.csdn.net/zhaostrong/article/details/86155569