自己实现call、apply.md
cooljser 2021-08-27  javascript
# call
Function.prototype.call1 = function (context) {
  context = context || window;
  context.fn = this;
  var args = [];
  for (let i = 1, len = arguments.length; i < len; i++) {
    args.push('arguments[' + i + ']');
  }
  var result = eval('context.fn(' + args + ')');
  delete context.fn;
  return result;
};
1
2
3
4
5
6
7
8
9
10
11
2
3
4
5
6
7
8
9
10
11
# apply
Function.prototype.apply1 = function (context, arr) {
  context = context || window;
  context.fn = this;
  var result;
  if (!arr) {
    result = context.fn();
  } else {
    var args = [];
    for (let i = 1, len = arr.length; i < len; i++) {
      args.push('arr[' + i + ']');
    }
    result = eval('context.fn(' + args + ')');
  }
  delete context.fn;
  return result;
};
Function.prototype.apply2 = function (ctx, arr) {
  ctx = Object(ctx) || (typeof window === 'undefined' ? {} : window);
  ctx.fn = this;
  let result = ctx.fn(...(arr || []))
  delete ctx.fn;
  return result;
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
