方法的泛化/方法的借用

Posted by CodingWithAlice on March 22, 2025

方法的泛化/方法的借用

将方法从对象中“解绑”出来,使其可以作为一个普通函数使用

  • 实现
Function.prototype.uncurry = function () {
    const self = this;
    return (...arg) => {
        // 方式1
        const obj = [].shift.call(arg);
        return self.apply(obj, arg);
        // 方式2
        return Function.prototype.call.apply(self, arg);
    };
};
  • 调用:将一个方法(通常是绑定到对象上的方法)转换为一个可以独立调用的函数
const obj = {
    value: 10,
    add: function (x, y) {
        return this.value + x + y;
    }
};
const uncurriedAdd = obj.add.uncurry();
console.log(uncurriedAdd(obj, 2, 3)); // 输出 15