如何删除.bind()的上下文参数

时间:2016-06-15 17:49:01

标签: javascript function metaprogramming bind currying

在查看this answer之后,如果可以重新分配addTogether.bind,我就会感到好奇,这样你就可以在没有上下文参数的情况下调用它。我尝试过的一些不同的方法如下:

// these are intended as separate attempts, don't execute all of them sequentially
addTogether.bind = addTogether.bind.bind(addTogether.bind);
addTogether.bind = addTogether.bind.bind(addTogether.bind(addTogether));
addTogether.bind = addTogether.bind.bind(addTogether);
addTogether.bind = addTogether.bind(addTogether);

我的意图是允许这样:

function addTogether(a,b) {
    return a+b;
}

// something here to make the following possible

console.log(typeof addTogether.bind(2)); // "function"
console.log(addTogether.bind(2)(3)); // 5
console.log(addTogether(2,3)); // 5

2 个答案:

答案 0 :(得分:1)

不,不可能省略Function.prototype.bind的上下文参数。你可以这样做

function addTogether(a,b) {
    return a+b;
}
addTogether_bind = (Function.prototype.bind).bind(addTogether, null);
//                                                                ^^^^
console.log(typeof addTogether_bind(2)); // "function"
console.log(addTogether_bind(2)(3)); // 5
console.log(addTogether(2,3)); // 5

答案 1 :(得分:0)

您需要更改Function.prototype,如下所示:

Function.prototype.partiallyApply = function(...args) {
   return this.bind(null, ...args);
};

然后你可以打电话

const addTwo = addTogether.partiallyApply(2);

您也可以直接修改.bind()

  1. 唐'吨
  2. 你需要暂时保留旧的,以便你可以打电话给它
  3. 不,真的。唐'吨