javascript 继承

初识js的继承机制,整理一下,以备日后复习和查阅。

  1 对象冒充

function classA(color){
    this.color=color;
    this.sayColor=function (){
        alert("A:"+this.color);
    };
}

function classB(color,name){
    this.newMethod=classA;
    this.newMethod(color);
    delete this.newMethod;
    this.name=name;
    this.sayName=function(){
        alert("B:"+this.name);
    };
}

var ca=new classA("red");
var cb=new classB("blue","jiujiu");
ca.sayColor();  //red
cb.sayColor();  //blue
cb.sayName();  //jiujiu

  2 call()方法

  call()方法第一个参数用作this的对象,其他参数直接传给函数本身。

  function sayColor(sPrefix,sSurfix){
    alert(sPrefix+this.color+sSurfix);
}
var obj=new Object();
obj.color="red";
sayColor.call(obj,"color "," is beautiful");   //color red is beautiful

  3 apply()方法

  使用与call()同,只不过后面参数是通过数组传入。

  sayColor.apply(obj,new Array("color "," is beautiful"));   //color red is beautiful

  4 原型方式

  function ClassA(){}
  ClassA.prototype.color="red";
  ClassA.prototype.sayColor=function(){
      alert(this.color);
  };
  function ClassB(){}
  ClassB.prototype=new ClassA();
  ClassB.prototype.name="jiujiu";
  ClassB.prototype.sayName=function (){
      alert(this.name);
  };

  var oa=new ClassA();
  var ob=new ClassB();
  ob.color="blue";
  oa.sayColor();   //red
  ob.sayColor();   //blue
  ob.sayName();   //jiujiu

  5 混合方式
  function ClassA1(color){
      this.color=color;
  }
  ClassA1.prototype.sayColor=function(){
      alert(this.color);
  };
  function ClassB1(color,name){
      ClassA1.call(this,color);
      this.name=name;
  }
  ClassB1.prototype=new ClassA1();
  ClassB1.prototype.sayName=function (){
      alert(this.name);
  };
  var oa1=new ClassA1("red1");
  var ob1=new ClassB1("blue1","jiujiu1");
  oa1.sayColor();
  ob1.sayColor();
  ob1.sayName();

posted @ 2013-03-21 18:03  猫九九  阅读(95)  评论(0编辑  收藏  举报