zoukankan      html  css  js  c++  java
  • JS中的Call()和Apply()

    1.常用实例

    function add (a,b){

      alert(a+b);

    }

    function sub(a,b){

      alert(a-b);

    }

    add.call(sub,4,3);相当于add(4,2);

    2.改变作用哉

    function Animal(){

      this.name="Animal";

      this.showName=function(){

        alert(this.name);

      }

    }

    function Cat(){

      this.name="Cat";

    }

    var animal=new Animal();

    var cat=new Cat();

    //通过call或apply方法,将原本属于Animal对象的showName()方法交给对象cat来使用了,即使Cat有同名showName方法也不会执行。

    animal.showName.call(cat,",")==animal.showName.apply(cat,[]);  输出结果为Cat

    3.实现继承

     function Animal(name){

      this.name=name;

      this.showName= function(){

        alert(this.name);

      }

    }

    function Cat(name){

    //Animal.call(this) 的意思就是使用 Animal对象代替this对象,那么 Cat中不就有Animal的所有属性和方法了吗,Cat对象就能够直接调用Animal的方法以及属性了.

      Animal.call(this, name);

    }

    var cat = new Cat("Black Cat");

    cat.showName();

    4.多重继承

    function Class10(){

      this.showSub= function(a,b){

        alert(a-b);

      }

    }

    function Class11(){

      this.showAdd = function(a,b){

        alert(a-b);

      }

    }

    function Class2(){

      Class10.call(this);

      Class11.call(this);

    }

  • 相关阅读:
    Qt进程间通信
    reinterpret
    vs调试技巧
    利用QSystemSemaphore和QSharedMemory实现进程间通讯
    QLocalSocket
    QShareMemory
    qt动态库实现无边框窗体的消息处理 nativeEvent的使用
    BCB6常用快捷键
    1219个人总结
    冲刺二 12.6
  • 原文地址:https://www.cnblogs.com/liangxuru/p/4738924.html
Copyright © 2011-2022 走看看