zoukankan      html  css  js  c++  java
  • call apply bind的用法

    在Javascript 中,call、apply 和bind 是Function对象自带的三个方法,这个三个方法主要作用是改变函数中的this指向。

    apply 、 call 、bind 三者都是用来改变函数的this对象的指向的;
    apply 、 call 、bind 三者第一个参数都是this要指向的对象,也就是想指定的上下文(函数的每次调用都会拥有一个特殊值——本次调用的上下文(context)——这就是this关键字的值。);
    apply 、 call 、bind 三者都可以利用后续参数传参;
    bind 是返回对应函数,便于稍后调用;apply 、call 则是立即调用 

    call();

    语法:call([thisObj[,arg1[, arg2[, [,.argN]]]]])

    定义:调用一个对象的一个方法,以另一个对象替换当前对象

    说明:call方法可以用来代替另一个对象调用一个方法

    call方法可将一个函数的对象上下文从初始的上下文改变为由 thisObj指定的新对象

    thisObj的取值有以下4种情况:
    (1) 不传,或者传null,undefined, 函数中的this指向window对象
    (2) 传递另一个函数的函数名,函数中的this指向这个函数的引用
    (3) 传递字符串、数值或布尔类型等基础类型,函数中的this指向其对应的包装对象,如 String、Number、Boolean
    (4) 传递一个对象,函数中的this指向这个对象

    function a(){   
      console.log(this);   //输出函数a中的this对象
    }       
    function b(){}       
    var c={name:"call"};    //定义对象c  
    a.call();   //window
    a.call(null);   //window
    a.call(undefined);   //window
    a.call(1);   //Number
    a.call('');   //String
    a.call(true);   //Boolean
    a.call(b);   //function b(){}
    a.call(c);   //Object

    function class1(){   
      this.name=function(){   
        console.log("我是class1内的方法");   
      }   
    }   
    function class2(){ 
      class1.call(this);  //此行代码执行后,当前的this指向了class1(也可以说class2继承了class1)   
    }   
    
    var f=new class2();   
    f.name();   //调用的是class1内的方法,将class1的name方法交给class2使用
    例子:
    function eat(x,y){   
      console.log(x+y);   
    }   
    function drink(x,y){   
      console.log(x-y);   
    }   
    eat.call(drink,3,2) //5


    function Animal(){   
      this.name="animal";   
      this.showName=function(){   
        console.log(this.name);   
      }   
    }   
    function Dog(){   
      this.name="dog";   
    }   
    var animal=new Animal();   
    var dog=new Dog();       
    
    animal.showName.call(dog);
    
    输出:dog








  • 相关阅读:
    SVN trunk(主线) branch(分支) tag(标记) 用法详解和详细操作步骤
    svn branch and merge(svn切换分支和合并)详解
    WPF 后台任务 等待动画 样例 && C# BackgroundWorker 详解
    WPF CheckBox 滑块 样式 开关
    WPF自适应可关闭的TabControl 类似浏览器的标签页
    Bootstrap WPF Style(二)--Glyphicons 字体图标
    WPF 中的 Pack URI地(资源文件加载)
    Bootstrap WPF Style,Bootstrap风格的WPF样式
    tomcat修改server.xml的虚拟目录,启动eclipse后清空
    js修改css属性值
  • 原文地址:https://www.cnblogs.com/qingcui277/p/10412984.html
Copyright © 2011-2022 走看看