gpt4 book ai didi

javascript - 有没有办法访问函数的预绑定(bind)值?

转载 作者:太空宇宙 更新时间:2023-11-04 00:31:16 24 4
gpt4 key购买 nike

像这样:

const a = (arg0, arg1, arg2) => {
console.log(arg0);
};
const b = a.bind(null, 1, 2, 3)

现在假设我只有b,是否可以获取a的预绑定(bind)值列表?我的意思是值 1, 2, 3

如果可以的话,如何实现?

最佳答案

如果您编写自己的绑定(bind)函数,则可以向其附加新属性,函数可以像任何其他对象一样添加属性。

function bind(fn, thisArg, ...boundArgs) {
const func = function(...args) {
return fn.call(thisArg, ...boundArgs, ...args)
}
// you can hide the properties from public view using
// defineProperties, unfortunately they are still public
Object.defineProperties(func, {
__boundArgs: { value: boundArgs },
__thisArg: { value: thisArg },
__boundFunction: { value: fn }
})
return func
}

const a = (a, b, c) => console.log(a, b, c)

const b = bind(a, null, 1, 2, 3)

b()

console.log(b.__boundArgs)
console.log(b.__thisArgs)
console.log(b.__boundFunction)
<script src="http://codepen.io/synthet1c/pen/WrQapG.js"></script>

Function.prototype.bind 的第一个参数是 this arg。

要回答这个问题,如果您使用的是 Chrome,您可以访问绑定(bind)函数的属性 [[BoundArgs]] 中的信息。运行代码并检查您的控制台

const a = (arg0, arg1, arg2) => {
console.log(arg0, arg1, arg2);
};
const b = a.bind(null, 1, 2, 3)
b()
console.dir(b)

关于javascript - 有没有办法访问函数的预绑定(bind)值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40863767/

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