2016.4.19—js继承(学习笔记)

来源:互联网 发布:linux全部删除 编辑:程序博客网 时间:2024/05/20 19:16

1.继承的方式

  • 对象冒充
function ClassA(sColor){    this.color=sColor;    this.sayColor=function(){        alert(this.color);    };}function ClassB(sColor){    this.newMethod=ClassA;    this.newMethod=ClassA(sColor);    delete this.newMethod;}

这种方法可以支持多重继承,但存在一个弊端,如果实现多继承,可能出现超类中有相同的属性或者是方法,但最后的类具有优先级(覆盖前面的)。—>Function对象中加了两个新方法call()和apply().

  • call()方法
    第一个参数用作this的对象,其他的参数直接传递给函数自身
function ClassB(sColor,sName){    //this.newMethod=ClassA;    //this.newMethod=ClassA(sColor);    //delete this.newMethod;    ClassA.call(this,sColor);    //ClassA中的关键字this等于新创建的ClassB对象    this.name=sName;    this.sayName=function(){        alert(this.name);    }}
  • apply()方法
    apply()方法有两个参数,用作this的对象和要传递给函数的参数的数组
function ClassB(sColor,sName){    //this.newMethod=ClassA;    //this.newMethod=ClassA(sColor);    //delete this.newMethod;    ClassA.apply(this,new Array(sColor));    ClassA.apply(this,arguments)    this.name=sName;    this.sayName=function(){        alert(this.name);    }}

上面两种方法都可以①的第二个参数是只有一个值的color的数组;②也可以吧ClassB的整个arguments对象作为第二个参数传递给apply()方法。
注意:只有超类中的参数顺序与子类的参数顺序完全一致时才可以传递参数对象,如不一致就要创建一个单独的数组,按正确的顺序放置参数。

  • 原型链
function ClassA{}ClassA.prototype.color="red";ClassA.prototype.sayColor=function(){    alert(this.color);}function ClassB{}//在调用ClassA的构造函数时没有传递参数,在原型链中要确保构造函数中没有任何参数——>所以产生了混合方式ClassB.prototype=new ClassA();

子类的所有属性和方法都必须出现在prototype属性被赋值后,应为在它之前赋值的所有方法都被删除

  • 混合方式
function ClassA(sColor){    this.color=sColor;}ClassA.prototype.sayColor=function(){    alert(this.color);}function ClassB(sColor,sName){    ClassA.call(this,sColor);    this.name=sName;}ClassB.prototype=new ClassA();ClassB.prototype.sayName=function(){    alert(this.name);}
0 0