forked from fireairforce/leetCode-Record
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path实现apply.js
50 lines (48 loc) · 1.2 KB
/
实现apply.js
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
42
43
44
45
46
47
48
49
50
Function.prototype.myapply = function(context) {
if (typeof this !== "function") {
throw new TypeError("not function");
}
// 如果传递的执行上下文为null,就将环境切换为window
context = context || window;
// 然后在context对象上新建一个属性,是一个函数
context.fn = this;
// 这个地方是取参数
let result;
if (arguments[1]) {
result = context.fn(...arguments[1]);
} else {
result = context.fn();
}
// 删除了这个属性
delete context.fn;
return result;
};
Function.prototype.Myapply = function(context = window, args) {
if (typeof this !== "function") {
throw new TypeError("不是函数");
}
context = context || window;
context.fn = this;
if (Array.isArray(args)) {
result = context.fn(...args);
} else {
result = context.fn();
}
delete context.fn;
return result;
};
Function.prototype.MyApply = function(context, arg) {
if (typeof this !== "function") {
throw new TypeError(`not function`);
}
let fn = new Symbol();
context[fn] = this;
let result;
if (Array.isArray(arg)) {
result = context[fn](...arg);
} else {
result = context[fn]();
}
delete context.fn;
return result;
};