[英]Correctly bind to Javascript function parameter
I got a method which receives 2 parameters:我得到了一个接收 2 个参数的方法:
function func(param1, param2){...
I got a React component which receives a function as a parameter and it has the information about the 2nd parameter, and I want to set the first parameter in this case as a constant.我有一个 React 组件,它接收一个函数作为参数,它有关于第二个参数的信息,我想在这种情况下将第一个参数设置为常量。
What I'm doing is:我正在做的是:
let myFuncToPass = func.bind("const value", null);
.
.
.
<ComponentName funcParam = { (res) => myFuncToPass(res) }
.
I was expecting that when the callback is invoked, the parameter will be called with "const value" as the first parameter and the res
as the 2nd.我期待当回调被调用时,参数将被调用,“const value”作为第一个参数,
res
作为第二个参数。 What happens is that the res is received as it should to the 2nd parameter, but the first one is null instead of "const value"发生的情况是 res 被接收到第二个参数,但第一个是 null 而不是“const value”
What did I do wrong here?我在这里做错了什么?
I think you want to do this:我想你想这样做:
let myFuncToPass = func.bind(this, "const value");
[edit] the first argument won't necessarily be this
, it depends entirely on your usecase -- if func
never uses this
internally it probably doesn't matter at all, or you may prefer to pass null
in -- you'll need to think about that question for yourself [编辑] 第一个参数不一定是
this
,它完全取决于您的用例——如果func
从不this
内部使用它,它可能根本不重要,或者您可能更愿意传入null
—— 你需要自己思考这个问题
the first argument binds what this
means when the resulting function is called, and the second argument defines the first argument passed to the function当调用结果函数时,第一个参数绑定
this
意味着什么,第二个参数定义传递给函数的第一个参数
[edit] [编辑]
Just do this as an experiment:只需将其作为实验即可:
function x() {
console.log(this);
console.log(arguments);
}
x();
x.bind({a:2}, "first argument")("second argument");
Look to docs: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_objects/Function/bind查看文档: https : //developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_objects/Function/bind
Bind function first parameter is this .绑定函数的第一个参数是this 。
To use a partial application, you should use babel or a functional library like Ramdajs or write like this.要使用部分应用程序,您应该使用 babel 或 Ramdajs 之类的函数库或这样编写。
func.bind('irrelevant', 'const value')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.