apply和call方法的作用

305 阅读2分钟

apply和call方法的作用

  • 专门用于修改方法内部的this
    function text() {
      /**
       *未使用apply之前this指向调用者window
       * 使用apply之后this指向obj 
       */
      console.log(this);
    }
    let obj = { name: "小宝成", age: 26 };
    /**
     * window.text.apply(obj)
     * 1.通过window.text找到text方法
     * 2.通过apply(obj)找到的text方法内部的this修改为自定义的对象
     */

    // window.text.apply(obj)
    window.text.call(obj)
  • apply和call方法传参
    • apply(['希望this指向的对象'],['参数一','参数二','参数三','参数四','参数五','参数六',...])
    function sum(a, b) {
        console.log(this);
        console.log(a + b);
      }
      let obj = { name: "小宝成", age: 26 };
      /**
       * window.text.apply(obj)
       * 1.通过window.text找到text方法
       * 2.通过apply(obj)找到的text方法内部的this修改为自定义的对象
       * 3.将传入数组中的元素依次取出,传递给形参
       */
      // window.sum.apply(obj, [1, 2])
    
      // let arr = [];
      // arr.push(1);
      // console.log(arr);
    
      /**
       * 真数组转换成伪数组的过程
       * 1.通过[].push找到数组中的push方法
       * 2.通过apply(obj)找到的push方法内部的this修改为自定义的对象
       * 3.将传入数组中的元素依次取出,传递给形参
       */
      let arr = [1, 2, 5, 7, 9];
      let obj1 = {};
      [].push.apply(obj1, arr)//等同于 obj1.push(['arr中的每一项'])
      console.log(obj1);//index.html:49 {0: 1, 1: 2, 2: 5, 3: 7, 4: 9, length: 5}
    
    • call(['希望this指向的对象'],'参数一','参数二','参数三','参数四','参数五','参数六',...)
    function sum(a, b) {
        console.log(this);
        console.log(a + b);
      }
      let obj = { name: "小宝成", age: 26 };
      /**
       * window.text.call(obj)
       * 1.通过window.text找到text方法
       * 2.通过call(obj)找到的text方法内部的this修改为自定义的对象
       * 3.将传入数组中的元素依次取出,传递给形参
       */
      // window.sum.call(obj, ...[1, 2])
    
      // let arr = [];
      // arr.push(1);
      // console.log(arr);
    
      /**
       * 真数组转换成伪数组的过程
       * 1.通过[].push找到数组中的push方法
       * 2.通过call(obj)找到的push方法内部的this修改为自定义的对象
       * 3.将传入数组中的元素依次取出,传递给形参
       */
      let arr = [1, 2, 5, 7, 9];
      let obj1 = {};
      [].push.call(obj1, ...arr)//等同于 obj1.push(['arr中的每一项'])
      console.log(obj1);//index.html:49 {0: 1, 1: 2, 2: 5, 3: 7, 4: 9, length: 5}