zoukankan      html  css  js  c++  java
  • 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();

  • 相关阅读:
    网站建设问题
    14.2.2.1 InnoDB Lock Modes
    14.2.2 The InnoDB Transaction Model and Locking InnoDB 事务模型和锁定
    Python_编程特色
    Python_编程特色
    Tk日志查看程序
    Linux_进程管理&计划任务
    Linux_进程管理&计划任务
    严重: StandardWrapper.Throwable
    Java导出Excel三表头
  • 原文地址:https://www.cnblogs.com/zwr99/p/2973944.html
Copyright © 2011-2022 走看看