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

const obj = { name: 'jiujue', age: 18 }

function print(...args) {
console.log(this)
console.log(...args)
}
print.myCall(obj, 1, 2, 3)
Function.prototype.myCall = function(context = window) {
if (typeof this !== 'function') {
throw new TypeError('need a function')
}
context.fn = this
const args = [...arguments].slice(1)
const res = context.fn(...args)
delete context.fn
return res
1
}

Function.prototype.myApply = function(context = window) {
if (typeof this !== 'function') {
throw new TypeError('need a function')
}
context.fn = this
if (arguments[1]) {
let res = context.fn(...arguments[1])
} else {
let res = context.fn()
}

delete context.fn
return res
}

const obj = { name: 'jiujue', age: 18 }

function print(...args) {
console.log(this)
console.log(...args)
}
let p = print.myBind(obj)
p(1, 2, 3)
Function.prototype.myBind = function(context = window) {
if (typeof this !== 'function') {
throw TypeError('left value need a function')
}
context.fn = this
const args = [...arguments].slice(1)
return function(..._args) {
const res = context.fn(args.concat(_args))
delete context.fn
return res
}
}