# 题目描述

请你自定义一个函数实现Function.call方法

# 分析

call 首先改变了 this 的指向,使函数的 this 指向了 foo,然后使 bar 函数执行了

  • 获取传来的参数,如果没有修改this指向,就默认为window
  • 获取谁调用了myCall —— this,将this绑定到传入的对象上
  • 调用对象该属性,即是执行调用myCall的函数,同时绑定了this为传入的对象
  • 删除该属性,返回函数调用即可

TIP

myCall第一个参数是传入的this myCall的第二个参数和第三个参数才是传入test的第一个参数和第二个

# 代码实现

Function.prototype.myCall = function(context){
    context = context || window;
    context.fn = this;  // 把调用call的函数绑定到传入第一个参数的对象上
    const args = [...arguments].slice(1);
    const result = context.fn(args);
    delete context.fn;
    return result;
}

// 测试
function test(arg1, arg2) {
  console.log("第一个参数是: ", arg1);
  console.log("第二个参数是: ", arg2);
  console.log("执行test的this是: ", this);
  console.log(this.a, this.b);
}

// 执行test
// call第一个参数是传入的this, 
// call的第二个参数和第三个参数才是传入test的第一个参数和第二个参数

test.myCall(
  {
    a: '我是a',
    b: '我是b',
  },
  1,
  2
);
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
29

测试结果如下

1