# 题目描述

请用自定义函数来实现Function.bind()

# 思路

  • bind 函数虽然也能改变 bar 函数的 this,
  • 但是改变后,函数并不会执行,只是返回一个新的函数,
  • 想执行就得继续调用,
  • 执行xxx.bind() 不会执行
  • xxx.bind()() 才会执行

bind 接受两个参数

  • 第一个参数是要绑定的this
  • 第二个参数是要给执行bind的函数传的参数

# 代码实现

var foo = {
  a: "我是a",
};

function test() {
  console.log("this.a: ", this.a);
}

console.log("原生bind如下: ");
test();
test.bind(foo)();
// bind 函数虽然也能改变 bar 函数的 this,
// 但是改变后,函数并不会执行,只是返回一个新的函数,
// 想执行就得继续调用,仔细观察第五行代码的写法。

// bind 接受两个参数

Function.prototype.myBind = function (target, ...arguments1) {
  return (...arg2) => {
    // 获取要传入的参数
    const arg = arguments1.concat(arg2);
    return this.call(target, ...arg);
  };
};

console.log("myBind如下: ");
test();
test.myBind(foo)();
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28

测试结果如下 👇

1

: