如何获取由JavaScript的.bind()函数绑定的参数

4

如何获取绑定到函数的参数?

function add(x){
  return x + 1
}

var func = add.bind(null, x)
// how do I get the value of `x` from the `func` variable alone?

你已经检索到了变量,现在它存储在func中。这不是你想要的吗? - Ousmane D.
2
上面的代码只是一个例子,在我拥有 func 变量的上下文中,我没有原始参数。 - Rob
1
我认为你做不到。 - evolutionxbox
1
你可以在控制台下看到它,位于[[BoundArgs]]之下,但我认为这在代码中是不可访问的。 - evolutionxbox
1
是的,在我的上下文中,我可以看到它是[[Scopes]],在控制台中,您可以右键单击并按“复制属性路径”,它会给出正确的路径,但尝试评估它会抛出一个错误,说它未定义...只是出于好奇,您如何在控制台中看到[[BoundArgs]]?我正在尝试使用我的示例,但我什么也看不到。 - Rob
@Rob,你可以通过执行以下命令查看它:console.dir(func) - KevBot
1个回答

2
你无法原生实现绑定,但你可以轻松地创建自己的类似bind的函数:
function bind(fn, boundThis, ...args) {
  const bound = fn.bind(boundThis, ...args)
  bound.__targetFunction__ = fn;
  bound.__boundThis__ = boundThis;
  bound.__boundArgs__ = args
  return bound;
}

您可以像使用Function.prototype.bind一样使用它,但您还可以访问绑定的值和原始函数:

function addOne(x) {
  return x + 1
}
const two = bind(addOne, null, 1)
console.log(two())  // print 2
console.log(two.__boundArgs__)  // print [1]

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接