Record your life!
DashboardMy Blogs
如何实现一个自定义的bind函数
Diary
lifejavascript
By sakopqiu2025-10-10 15:17

众所周知,JS原生提供一个Function.prototype.bind函数。

面试中经常会遇到这个函数是怎么实现的问题,下面尝试解答下

假设你要实现一个myBind函数,下面的代码里给出了myBind的实现和具体的使用

Function.prototype.myBind = function(context, ...args){
    // 因为这里在Function.prototype上定义的,this就是函数本身,即test
    const originalFunc = this;
    return function (...moreArgs) {
        const symbol = Symbol.for("temp");
        context[symbol] = originalFunc;
        const result = context[symbol](...args, ...moreArgs);
        delete context[symbol]
        return result;
    }
}

function test(count1, count2) {
    console.log(this.name + " has " + count1 + " apples and " + count2 + " oranges");
}
const person = { name: "oliver" };

// 这里绑定了this和123,但是test函数还有count2这个参数,下面的例子中会把那个参数也用上
const boundedFunc = test.myBind(person, 123);

boundedFunc(456); // 应该打印 oliver has 123 apples and 456 oranges
Edit