call
function call(fn, obj, ...arg) { //call 在非严格模式下,obj为null或者undefined时,this指向globalThis if (obj === undefined || obj === null) { obj = globalThis } //给obj添加临时方法 obj.temp = fn //调用temp方法 let res = obj.temp(...arg) //删除临时方法 delete obj.temp //返回res return res}
<!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <script src="./index.js"></script> </head> <body> <script type="text/javascript"> function add(a, b) { console.log(this) return a + b + this.c } let obj = { c: 521 } window.c = 1234 console.log(call(add, obj, 10, 20)) console.log(call(add, null, 10, 20)) </script> </body></html>
apply
function apply(fn, obj, arg) {
//call 在非严格模式下,obj为null或者undefined时,this指向globalThis
if (obj === undefined || obj === null) {
obj = globalThis
}
//给obj添加临时方法
obj.temp = fn
//调用temp方法
let res = obj.temp(...arg)
//删除临时方法
delete obj.temp
//返回res
return res
}
bind
function bind(fn, obj, ...arg) {
return function () {
return call(fn, obj, ...arg)
}
}