gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 14:28:24 27 4
gpt4 key购买 nike

如何获取已绑定(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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com