JavaScript this 指针概括(apply、call、bind)

概述

一个函数中this的指向是由调用这个函数的环境来决定的。
  1. 全局数组

    var a = 1;
    function b(){
        var a = 2;
        console.log(this.a);
    };
    b(); //1
    <input type="text" value="4" onclick="b()" />
    
    var value = 3;
    function b(){
        console.log(this.value);
    };
    b();//3
    此时的b函数的环境是全局的
  2. 局部app

    var a = 1;
       var c = {a:3};
       c.b = function(){
       var a = 2;
       console.log(this.a);
       };
       c.b();//3
       
      //当即执行函数 因为是赋值,因此只执行了右边的函数
      var a = 1;
      var c = {a:3};
      (c.b = function(){
      var a = 2;
      console.log(this.a);
      })();//1

apply、call 和 bind 改变this指向

  1. apply函数

    • 参数this

      只能传两个参数,第一个参数a是 改变this指向的结果对象(在非严格模式下,第一个参数为null或者undefined时会自动替换为指向全局对象),第二个参数是传给a的 参数集合(arguments[数组或类数组])
    • 实例code

      var a = 1;
      var c = {a : 3};
      function b(d,e){
          var a = 2;
          console.log(this.a);
          console.log(d,e);
      };
      b.apply(c);//3  undefined undefined
      b.apply();//1  undefined undefined
      b.apply(c,[5,6]);// 3  5 6
  2. call对象

    • 参数input

      第一个参数和apply()的第一个参数同样,不一样的是apply()后面是接收一个数组或类数组,call()后面是是接收的参数列表。
    • 实例io

      var a = 1;
      var c = {a : 3};
      function b(d,e){
          var a = 2;
          console.log(this.a);
          console.log(d,e);
      };
      b.call(c);//3  undefined undefined
      b.call();//1  undefined undefined
      b.call(c,5,6);// 3  5 6
  3. bindconsole

    • 参数function

      参数和call同样,不一样的是 call()和apply()在调用函数以后会当即执行,而bind()方法调用并改变函数运行时上下文后,返回一个新的函数,供咱们须要时再调用。
    • 实例

      var a = 1;
      var c = {a : 3};
      function b(d,e){
         var a = 2;
         console.log(this.a);
         console.log(d,e);
      };
      var b1 = b.bind(c);
      var b2 =b.bind();
      var b3 =b.bind(c,5,6);
      b1();//3  undefined undefined
      b2();//1  undefined undefined
      b3()// 3  5 6
相关文章
相关标签/搜索