javascript 继承

    xiaoxiao2025-10-23  9

    原型链:利用原型让一个引用类型继承另一个引用类型的属性和方法。

    function SuperType(){ this.property=true; } SuperType.prototype.getSuperValue=function(){ return this.property; }; function SubType(){ this.subproperty=false; } SubType.prototype=new SuperType();//继承SuperType SubType.prototype.getSubValue=function(){ return this.subproperty; } var instance=new SubType(); alert(instance.getSubValue());//false alert(instance.getSuperValue());//true注意:子类型有时候需要重写超类型中的某个方法,或者需要添加超类型中不存在的某个方法。但不管怎样,给原型添加方法的代码一定要放在替换原型的语句之后。

    function SuperType(){ this.property=true; } SuperType.prototype.getSuperValue=function(){ return this.property; }; function SubType(){ this.subproperty=false; } //继承SuperType SubType.prototype=new SuperType(); //添加新方法 SubType.prototype.getSubValue=function(){ return this.subproperty; } //重写超类型中的方法 SubType.prototype.getSuperValue=function(){ return false; } var instance=new SubType(); alert(instance.getSubValue());//false alert(instance.getSuperValue());//false

    不能使用对象字面量创建原型方法。

    原型链的问题:

    function SuperType(){ this.colors=["red","blue","green"]; } function SubType(){ } //继承 SubType.prototype=new SuperType(); var instance=new SubType(); instance.colors.push("black"); alert(instance.colors);//red,blue,green,black var instance2=new SubType(); alert(instance2.colors);//red,blue,green,black这个问题和在创建对象的时候也有,因为colors是共享属性。

    借用构造函数:使用apply() 和call() 方法

    function SuperType(){ this.colors=["red","blue","green"]; } function SubType(){ //继承 SuperType.call(this); } var instance=new SubType(); instance.colors.push("black"); alert(instance.colors);//red,blue,green,black var instance2=new SubType(); alert(instance2.colors);//red,blue,green function SuperType(name){ this.name=name; } function SubType(){ //继承 SuperType.call(this,"Nick"); this.age=29; } var instance=new SubType(); alert(instance.name);//Nick alert(instance.age);//29组合继承:将原型链和借用构造函数的技术组合到一起。 function SuperType(name){ thia.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.constructor=SubType; SubType.prototype.sayAge=function(){ alert(this.age); } var instance1=new SubType("Nick",29); instance1.colors.push("black"); alert(instance1.colors);//red,blue,green,black instance1.sayName();//Nick instance1.sayAge();//29 var instance2=new SubType("Greg",27); alert(instance1.colors);//red,blue,green instance1.sayName();//Greg instance1.sayAge();//27还有其他的一些继承方式比较少见的。

    转载请注明原文地址: https://ju.6miu.com/read-1303454.html
    最新回复(0)