实现call-apply-bind-new-柯里化
# 实现call-apply-bind-new-柯里化
// call
Function.prototype.call = function (context) {
// 实现call
context = Object(context) || globalThis;
const key = Symbol('fn');
let args = [...arguments].slice(1) || [];
context[key] = this;
let res = context[key](...args);
delete context[key];
return res;
}
// apply
Function.prototype.apply = function (context, args = []) {
context = Object(context) || globalThis;
const key = Symbol('fn');
context[key] = this;
let res = context[key](...args);
delete context[key];
return res;
}
// bind
Function.prototype.bind = function (context) {
if (typeof this !== 'function') {
throw new TypeError('请输入一个函数')
}
let args = [...arguments].slice(1);
let self = this;
let fBound = function() {
args = [...args, ...arguments];
return self.apply(this instanceof fBound ? this : context, args)
}
fBound.prototype = Object.create(this.prototype);
return fBound;
}
// new
function objectFactoryES6(func) {
if (typeof func !== 'function') {
throw new TypeError('请输入一个函数')
}
const args = [...arguments].slice(1)
let obj = Object.create(func.prototype)
let res = func.apply(obj, args)
let isFunction = typeof res === 'function'
let isObject = res !== 'null' && typeof res === 'object'
return isFunction || isObject ? res : obj;
}
// 柯里化
function curry(func) {
return function curried(...args) {
if (args.length === func.length) {
return func.apply(this, args)
} else {
return function subCurried(...args2) {
return curried.apply(this, [...args, ...args2]);
}
}
}
}
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65