JS手写apply、call、bind方法

一、js手写call:隐式绑定改变this
Function.prototype.customCall = function (thisArg, ...args) {
    // 1、获取被调用的函数
    const fn = this; // 这里的this指向sum

    // 2、绑定this,将thisArg转成对象类型(防止传入非对象类型)
    thisArg = thisArg ? Object(thisArg) : window;
    thisArg.fn = fn;

    // 3、执行函数
    const result = thisArg.fn(...args);
    delete thisArg.fn;

    // 4、返回执行结果
    return result;
};

function sum (num1, num2) {
    console.log('sum函数', this, num1, num2, num1 + num2); // sum函数 String{'abc', fn: ƒ} 10 20 30
    return num1 + num2;
}

sum.customCall('abc', 10, 20);
二、js手写apply:隐式绑定改变this
Function.prototype.customapply = function (thisArg, args) {
    // 1、获取被执行的函数
    const fn = this; // 这里的this指向sum函数

    // 2、绑定this
    thisArg = thisArg ? Object(thisArg) : thisArg; // 处理thisArg为Number/null/undefined的情况
    thisArg.fn = fn;

    // 执行函数
    const result = args ? thisArg.fn(...args) : thisArg.fn(); // args可能为undefined
    delete thisArg.fn;

    // 返回执行结果
    return result;
};

function sum(num1, num2) {
    console.log('sum被调用', this, num1, num2, num1 + num2); // sum被调用 String{'abc'} 10 20
    return num1 + num2;
}

function sum1(num) {
    console.log('sum1被调用', this, num); // sum1被调用 String{'abc', fn: ƒ} 10
    return num;
}

function sum2() {
    console.log('sum2被执行');
}

sum.customapply('abc', [10, 20]); // 隐式调用
sum1.customapply('abc', [10]);
sum2.customapply('abc');
三、js手写bind:隐式绑定改变this
Function.prototype.custombind = function (thisArg, ...args) {
    // 1、获取被调用的函数
    const fn = this;

    // 2、绑定this
    thisArg = thisArg ? Object(thisArg) : window;
    const retFunc = function (...extraArgs) {
        thisArg.fn = fn;
        const result = thisArg.fn(...args, ...extraArgs); // 对两次传入的参数进行合并
        delete thisArg.fn;
        return result;
     };

    // 3、直接返回方法,且这个方法绑定了执行参数
    return retFunc;
};

function sum(num1, num2) {
    console.log('sum被调用了', this, num1, num2, num1 + num2);
    return num1 + num2;
}

sum.custombind('abc', 10)(20);

另一种手写bind

Function.prototype.customBind = function() {
    // 获取要被执行的函数
    const fn = this;

    // 获取this
    let thisArg = Array.prototype.shift.call(arguments);
    thisArg = thisArg ? Object(thisArg) : window; // 必须,要保证thisArg是个Object

    // 获取参数
    const args = Array.prototype.slice.call(arguments);

    return function() {
      const extraArgs = Array.prototype.slice.call(arguments);
      // 绑定this
      thisArg.fn = fn;
      thisArg.fn(...args, ...extraArgs);
    };
}

function sum (num1, num2) {
    const result = num1 + num2;
    console.log('sum被调用', this, num1, num2, result);
    return result;
}

sum.customBind('abc', 10)(20); // sum被调用 String{'abc', fn: ƒ} 10 20 30
四、认识arguments:传递给函数的参数的类数组(array-like)对象

类数组对象:长的像一个数组,实际上是一个对象
1、拥有数组的一些特性,例如length、或可以通过index索引来访问
2、没有数组的一些方法,例如forEach、map等

// 认识arguments
 function sum(num1, num2, num3) {
    // 打印arguments
    console.log(arguments); // Arguments(3)[1, 2, 3, callee: ƒ, Symbol(Symbol.iterator): ƒ]

    // 常见的对arguments的操作有三个:
    // 1、获取参数长度
    console.log(arguments.length); // 3

    // 2、根据索引值获取某一个参数
    console.log(arguments[0]); // 1

    // 3、callee获取当前arguments所在的函数
    console.log(arguments.callee); // function sum(num1, num2, num3) {}
}
sum(1, 2, 3);
// 类数组转数组
function sum(num1, num2, num3) {
    // 方法一:自己遍历
    // const newArr = [];
    // for (let i = 0; i < arguments.length; i++) {
    //   newArr.push(arguments[i] * 2);
    // }
    // return newArr;

    // 方法二:slice(借助slice内部的遍历)
    // const newArr = Array.prototype.slice.call(arguments);
    // 或
    // const newArr = [].slice.call(arguments);
    // return newArr;

    // 方法三:ES6的from方法
    // const arr = Array.from(arguments);
    // return arr.map(v => v * 2);

    // 方法四:展开运算符
    const arr = [...arguments];
    return arr.map(v => v * 2);
}
sum(1, 2, 3);
// 箭头函数中没有arguments,会去上层作用域找
const hello = () => {
    // console.log(arguments); // arguments is not defined
};

const hi = function () {
    const fn = () => {
        console.log(arguments); // Arguments[123, callee: ƒ, Symbol(Symbol.iterator): ƒ]
    };
    return fn();
};

hello();
hi(123);
五、bind的一些面试题

       bind()方法主要就是将函数绑定到某个对象,bind()会创建一个函数,函数体内的this对象的值会被绑定到传入bind()中的第一个参数的值,例如:f.bind(obj),实际上可以理解为obj.f(),这时f函数体内的this自然指向的是obj;

  var a = {
    b: function() {
      var func = function() {
        console.log(this.c);
      }
      func();
    },
    c: 'hello'
  }
  a.b(); // undefined 这里的this指向的是全局作用域
  console.log(a.c); // hello
  var a = {
    b: function() {
      var _this = this; // 通过赋值的方式将this赋值给that
      var func = function() {
        console.log(_this.c);
      }
      func();
    },
    c: 'hello'
  }
  a.b(); // hello
  console.log(a.c); // hello
// 使用bind方法一
  var a = {
    b: function() {
      var func = function() {
        console.log(this.c);
      }.bind(this);
      func();
    },
    c: 'hello'
  }
  a.b(); // hello
  console.log(a.c); // hello

// 使用bind方法二
  var a = {
    b: function() {
      var func = function() {
        console.log(this.c);
      }
      func.bind(this)();
    },
    c: 'hello'
  }
  a.b(); // hello
  console.log(a.c); // hello
// 分析:这里的bind方法会把它的第一个实参绑定给f函数体内的this,所以里的this即指向{x:1}对象;
// 从第二个参数起,会依次传递给原始函数,这里的第二个参数2即是f函数的y参数;
// 最后调用m(3)的时候,这里的3便是最后一个参数z了,所以执行结果为1+2+3=6
// 分步处理参数的过程其实是一个典型的函数柯里化的过程(Curry)
  function f(y,z){
    return this.x+y+z;
  }
  var m = f.bind({x:1},2);
  console.log(m(3)); // 6
// 分析:直接调用a的话,this指向的是global或window对象,所以会报错;
// 通过bind或者call方式绑定this至document对象即可正常调用
  var a = document.write;
  a('hello'); // error
  a.bind(document)('hello'); // hello
  a.call(document,'hello'); // hello
// 实现预定义参数
// 分析:Array.prototype.slice.call(arguments)是用来将参数由类数组转换为真正的数组;
  function list() {
    return Array.prototype.slice.call(arguments);
  }
  var list1 = list(1, 2, 3); // [1,2,3]
// 第一个参数undefined表示this的指向,第二个参数10即表示list中真正的第一个参数,依次类推
  var a = list.bind(undefined, 10);
  var list2 = a(); // [10]
  var list3 = a(1, 2, 3); // [10,1,2,3]
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 第2章 基本语法 2.1 概述 基本句法和变量 语句 JavaScript程序的执行单位为行(line),也就是一...
    悟名先生阅读 4,195评论 0 13
  • 函数和对象 1、函数 1.1 函数概述 函数对于任何一门语言来说都是核心的概念。通过函数可以封装任意多条语句,而且...
    道无虚阅读 4,630评论 0 5
  • 函数只定义一次,但可能被执行或调用任意次。JS函数是参数化的,函数的定义会包括一个称为形参的标识符列表,这些参数在...
    PySong阅读 864评论 0 0
  • 依旧低飞的蜻蜓 在沟渠积水里映出自己 它们来不及逃跑或者飞高 阳光就散开了 空气里被一扫而空 干净的一览无余,大概...
    鹿原先生和蓬蒿阅读 1,009评论 6 30
  • 老师泄题,学校乱收费,刻意而为的打手,一切看分数的社会大势,甚至那些利用琳的有钱人,他们被遣返回国以后,也可以过着...
    张十九L阅读 299评论 0 0