function bindFn (...args) {
let context = args.shift() // 第一个参数为绑定的this
if (!context) throw new Error('no "this" object')
return (...rest) => {
// 这里的this指的是当前调用该方法的函数对象
this.apply(context, [...args, ...rest])
}
}
let testObj = {
value: 5
}
let testFn = function (a, b, c) {
console.log(this.value, a, b, c)
}
testFn.bindFn = bindFn
testFn = testFn.bindFn(testObj, 666, 888)
testFn(999) // 5 666 888 999
ES6实现bind函数
最新推荐文章于 2024-02-10 08:15:00 发布
本文介绍了一种自定义实现函数bind方法的方式,通过传递上下文对象和参数来改变函数调用时的this指向及预设参数。示例中展示了如何为函数绑定特定对象及其参数,并在调用时正确反映绑定效果。
937

被折叠的 条评论
为什么被折叠?



