-
Notifications
You must be signed in to change notification settings - Fork 0
/
call.js
35 lines (34 loc) · 866 Bytes
/
call.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
// ES3
Function.prototype.myCall = function(thisArg){
if(typeof this != 'function'){
throw new Error('The caller must be a function')
}
if(thisArg === undefined || thisArg === null){
thisArg = globalThis
} else {
thisArg = Object(thisArg)
}
const args = []
for(var i = 1;i < arguments.length;i ++){
args.push('arguments[' + i + ']')
}
thisArg.fn = this
const res = eval('thisArg.fn(' + args + ')')
delete thisArg.fn
return res
}
// ES6
Function.prototype.myCall = function(thisArg,...args){
if(typeof this != 'function'){
throw new Error('The caller must be a function')
}
if(thisArg === undefined || thisArg === null){
thisArg = globalThis
} else {
thisArg = Object(thisArg)
}
thisArg.fn = this
const res = thisArg.fn(...args)
delete thisArg.fn
return res
}