封装
function bind(fn, obj, ...args) {
return function () {
return call(fn, obj, ...args)
}
return function (...args2) {
return call(fn, obj, ...args, ...args2)
}
}
function call(fn, obj, ...args) {
if (obj === undefined || obj === null) {
obj = globalThis
}
obj.temp = fn
let result = obj.temp(...args)
delete obj.temp
return result
}
调用
<script>
function add(a, b) {
console.log(this)
return a + b + this.c
}
var obj = {
c: 50
}
window.c = 100
let fn = bind(add, obj, 10, 20)
console.log(fn())
let Fn = bind(add, obj)
console.log(Fn(10, 20))
</script>
结果
不传递参数
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/452f1128b42d1f03992c9e05d858f16e.png)
传递参数
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/7cfeef3577bd256ddbdb81223bd9c873.png)