如何删除 .bind() 的上下文参数
How to remove context argument of .bind()
看了 之后我很好奇是否可以重新分配 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
您需要更改 Function.prototype
,如下所示:
Function.prototype.partiallyApply = function(...args) {
return this.bind(null, ...args);
};
那你可以打电话
const addTwo = addTogether.partiallyApply(2);
也可以直接修改.bind()
但是
- 不要
- 您需要将旧的暂时保存在某个地方,以便您可以调用它
- 不,真的。不要。
不,不能省略 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
看了 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
您需要更改 Function.prototype
,如下所示:
Function.prototype.partiallyApply = function(...args) {
return this.bind(null, ...args);
};
那你可以打电话
const addTwo = addTogether.partiallyApply(2);
也可以直接修改.bind()
但是
- 不要
- 您需要将旧的暂时保存在某个地方,以便您可以调用它
- 不,真的。不要。
不,不能省略 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