javascript - 如何获取已被 JavaScript 的 .bind() 函数绑定(bind)的参数

标签 javascript google-chrome

如何获取已绑定(bind)到函数的参数?

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?

最佳答案

您不能在本地进行,但您可以轻松创建自己的类绑定(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 一样使用它但您还可以访问绑定(bind)值和原始函数:
function addOne(x) {
  return x + 1
}
const two = bind(addOne, null, 1)
console.log(two())  // print 2
console.log(two.__boundArgs__)  // print [1]

关于javascript - 如何获取已被 JavaScript 的 .bind() 函数绑定(bind)的参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42602954/

相关文章:

html - 列表标记在 Chrome 和 Safari 中消失在 Float : Left

javascript - 悬停特定框时如何将 jQuery 实现到特定类的类?

javascript - 如何对服务中调用的过滤器进行单元测试

javascript - 从 asp.net mvc 调用 javascript

HTML 表单验证弹出窗口在 Chrome 和 IE 中不可读

javascript - 如何使用 PDF.js 加载 Web 应用程序中包含的文件(不是来自 "file:"URL?

javascript - 网址正在更改,但内容未更新

javascript - 我们如何使用 Puppeteer 编写/自动化 Electron 应用程序?

javascript - 从 DOM 中删除添加的突出显示

javascript - 如何使用同一子域上的 URL 访问 iframe 的元素?