js

手写系列--apply/call/bind

手写apply/call/bind

Posted by AzirKxs on 2022-10-28
Estimated Reading Time 2 Minutes
Words 509 In Total
Viewed Times

手写系列–apply/call/bind

手写apply

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
Function.prototype.hyApply = function(thisArg,otherArgs){
//判断thisArg的类型并进行类型转换
thisArg = (thisArg === null || thisArg === undefined) ? window : Object(thisArg)

//thisArg.fn = this

//为thisArg设置fn属性并设置为不可枚举
Object.defineProperty(thisArg,'fn',{
configurable:true,
writable:true,
enuramble:false,
value:this
})
thisArg.fn(...otherArgs)
delete thisArg.fn
}


function foo(name,age){
console.log(this,name,age)
}

foo.hyApply('123',['kxs',22]) //String{'123'} 'kxs' 22

手写call

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
Function.prototype.hyCall = function(thisArg,...otherArgs){
//判断thisArg的类型并进行类型转换
thisArg = (thisArg === null || thisArg === undefined) ? window : Object(thisArg)

//thisArg.fn = this

//为thisArg设置fn属性并设置为不可枚举
Object.defineProperty(thisArg,'fn',{
configurable:true,
writable:true,
enuramble:false,
value:this
})
thisArg.fn(...otherArgs)
delete thisArg.fn
}


function foo(name,age){
console.log(this,name,age)
}

foo.hyCall('123','kxs',22) //String{'123'} 'kxs' 22

抽取合并apply和call

两个方法的逻辑基本相同,可以抽象成一个方法

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
function execFn(thisArg,otherArgs,fn){
//判断thisArg的类型并进行类型转换
thisArg = (thisArg === null || thisArg === undefined) ? window : Object(thisArg)

//thisArg.fn = this

//为thisArg设置fn属性并设置为不可枚举
Object.defineProperty(thisArg,'fn',{
configurable:true,
writable:true,
enuramble:false,
value:fn
})
thisArg.fn(...otherArgs)
delete thisArg.fn
}
Function.prototype.hyApply = function(thisArg,otherArgs){
execFn(thisArg,otherArgs,this)
}

Function.prototype.hyCall = function(thisArg,...otherArgs){
execFn(thisArg,otherArgs,this)
}

function foo(name,age){
console.log(this,name,age)
}
foo.hyCall('123','kxs',22) //String{'123'} 'kxs' 22
foo.hyApply('123',['kxs',22]) //String{'123'} 'kxs' 22

手写bind

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
Function.prototype.hyBind = function(thisArg,...otherArgs){
//判断thisArg的类型并进行类型转换
thisArg = (thisArg === null || thisArg === undefined) ? window : Object(thisArg)

//thisArg.fn = this

//为thisArg设置fn属性并设置为不可枚举
Object.defineProperty(thisArg,'fn',{
configurable:true,
writable:true,
enuramble:false,
value:this
})

return (...newArgs) => {
let args = [...otherArgs,...newArgs]
thisArg.fn(...args)
}
}

function foo(name,age){
console.log(this,name,age)
}

let newFoo = foo.hyBind('123','kxs')
newFoo(22) //String {'123', fn: ƒ} 'kxs' 22
newFoo(23) //String {'123', fn: ƒ} 'kxs' 23
newFoo(24) //String {'123', fn: ƒ} 'kxs' 24

如果这篇文章对你有帮助,可以bilibili关注一波 ~ !此外,如果你觉得本人的文章侵犯了你的著作权,请联系我删除~谢谢!