-
Notifications
You must be signed in to change notification settings - Fork 0
/
Function.js
56 lines (53 loc) · 1.36 KB
/
Function.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
51
52
53
54
55
56
Function.prototype.myCall = function (obj, ...args) {
obj = obj || globalThis
let fn = Symbol()
obj[fn] = this
setTimeout(() => {
delete obj[fn]
})
return obj[fn](...args)
}
Function.prototype.myApply = function (obj, args) {
obj = obj || globalThis
let fn = Symbol()
obj[fn] = this
setTimeout(() => {
delete obj[fn]
})
return obj[fn](...args)
}
Function.prototype.MyBind = function(obj, ...args) {
obj = obj || globalThis
let fn = Symbol()
obj[fn] = this
const _this = this
const res = function(...innerArgs) {
if (this instanceof _this) { //判断是不是new 操作
this[fn] = _this
this[fn](...args, ...innerArgs)
delete this[fn]
} else {
obj[fn](...args, ...innerArgs)
delete obj[fn]
}
}
res.prototype = Object.create(this.prototype)
return res
}
function myBind (obj = globalThis, ...args) {
let fn = Symbol()
obj[fn] = this
const _this = this
const res = function(...innerArgs) {
if (this instanceof _this) {
this[fn] = _this
this[fn](...args, ...innerArgs)
delete this[fn]
} else {
obj[fn](...args, ...innerArgs)
delete obj[fn]
}
}
res.prototype = Object.create(this.prototype)
return res
}