【问题标题】:Poly-fill for bind without call or applyPoly-fill 无需调用或应用即可绑定
【发布时间】:2022-11-04 20:21:01
【问题描述】:

我正在尝试为绑定函数编写 poly-fill 函数,而无需调用或应用方法。下面是代码,我怀疑如果“ctx”对象中已经有“fnToCall”方法会发生什么。执行以下操作将覆盖该功能,那么在不调用或应用的情况下编写多边形填充的正确/更好的方法是什么

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
  • 你能举个例子吗@kikon
  • 这是一个例子fiddle。当然,如果名称冲突是您面临的唯一问题,您可以设计一种简单的方法在循环中生成字符串,直到找到一个不是要将函数绑定到的对象的键,就像在这个fiddle
  • 由于小提琴中有错误,而且我看到没有其他答案,我将添加帖子作为答案

标签: javascript


【解决方案1】:

对您的代码和我之前在消息中的小改动进行小修正,基于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();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-04-18
    • 1970-01-01
    • 1970-01-01
    • 2019-11-11
    • 2012-07-12
    • 2018-04-22
    • 2012-11-30
    相关资源
    最近更新 更多