无需调用或应用即可进行绑定的多边形填充



我正在尝试为绑定函数编写poly-fill函数,而不需要调用或应用方法。下面是代码,我怀疑如果";ctx";对象具有";fnToCall";方法。执行以下操作将覆盖该函数,那么在不调用或应用的情况下编写poly-fill的正确/更好的方法是什么

Function.prototype.newBindWithoutApply = function (ctx, ...args) {

ctx.fnToCall = this;
// returning the new method with context
return function (...args1) {
allArguments = [...allArguments, ...args1]
return ctx.fnToCall(...args)
}
}

对您的代码和我以前在消息中的错误进行小的更正,基于Symbol的解决方案可以是:

Function.prototype.newBindWithoutApply = function (ctx, ...args) {
const fnToCall = Symbol();
ctx[fnToCall] = this;
return function (...args1) {
return ctx[fnToCall](...[...args, ...args1])
}
}
const o = {fnToCall: 1, fnToCall0: 2};
const f =  function(x, y, z){
console.log({"this":this, x, y, z});
}
const fBound = f.newBindWithoutApply(o, 11, 22);
fBound(33)
fBound(44)
const o2 = {fnToCall: 'a', fnToCall0: 'b'};
// binding an already bound function doesn't 
//change "this", but may bind unbound arguments
const fBound2 = fBound.newBindWithoutApply(o2, 99);
fBound2();

如果Symbol也不可用,可以通过在循环中更改函数的名称来避免名称冲突,直到找到一个不是绑定函数的对象的键:

Function.prototype.newBindWithoutApply = function (ctx, ...args) {
let fnToCall = "fnToCall";
let i = 0;
while(fnToCall in ctx){
fnToCall = "fnToCall"+i;
i++;
}
// "hide" the entry - enumerable is false by default
Object.defineProperty(ctx, fnToCall, {value: this});
return function (...args1) {
return ctx[fnToCall](...[...args, ...args1])
}
}
const o = {fnToCall: 1, fnToCall0: 2};
const f =  function(x, y, z){
console.log({"this":this, x, y, z});
}
const fBound = f.newBindWithoutApply(o, 11, 22);
fBound(33);
fBound(44);
const o2 = {fnToCall: 'a', fnToCall0: 'b'};
// binding an already bound function doesn't 
//change "this", but may bind unbound arguments
const fBound2 = fBound.newBindWithoutApply(o2, 99);
fBound2();

最新更新