简体   繁体   English

在对象中的Javascript函数中传递参数

[英]passing parameter in Javascript function in object

I have this object:我有这个对象:

{
    label: 'Field Label',
    key: 'field-key',
    operation: somefunctionWithParam(param)   
}

and function和功能

const = somefunctionWithParam(val) => {
    return format(val)
} 

Operation function gets called from somewhere and it passes the value back.操作函数从某处被调用并将值传回。 I need to pass a parameter from我需要传递一个参数

somefunctionWithParam(param)

and access it from where I call it so that value can be manipulated based on parameter.并从我调用它的地方访问它,以便可以根据参数操作值。

Operation function gets called from somewhere and it passes the value back操作函数从某处被调用并将值传回

This happens because you are invoking the function while assigning it to the key operation .发生这种情况是因为您在将函数分配给键operation时调用了该函数。

Change your code to将您的代码更改为

const somefunctionWithParam = (val) => {
    return format(val)
}

and you can assign the function to the key operation like this您可以将功能分配给这样的按键operation

const obj = {
    label: 'Field Label',
    key: 'field-key',
    operation: somefunctionWithParam   
}

Or you can define an anonymous function like this或者你可以像这样定义一个匿名函数

const obj = {
  label: 'Field Label',
  key: 'field-key',
  operation: (val) => {
      return format(val)
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM