js总结之模拟call,apply

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
30
31
32
33
34
35
36
37
38
39
40
41
/*
* @Author: changchang
* @github: https://github.com/changchangge
* @LastEditors: changchang
* @Date: 2019-02-27 16:50:58
* @LastEditTime: 2019-02-27 16:54:29
*/
Function.prototype.callTest = function (context) {
/**
* @description: 实现一个call函数
*/
var context = context || window;
context.fn = this;
var args = [];
for (var i = 1; i < arguments.length; i++) {
args.push("arguments[" + i + "]");
}
var result = eval("context.fn(" + args + ")")
delete context.fn;
return result;
}

Function.prototype.applyTest = function (context, arr) {
/**
* @description: 实现一个bind函数
*/
var context = context || window;
context.fn = this;
var result;
if (!arr) {
result = context.fn();
} else {
var args = [];
for (var i = 0; i < arr.length; i++) {
args.push("arr[" + i + "]");
}
result = eval("context.fn(" + args + ")")
}
delete context.fn;
return result;
}
本文结束啦感谢您的阅读
undefined