简体   繁体   中英

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 .

Change your code to

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

and you can assign the function to the key operation like this

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)
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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