简体   繁体   中英

Square Brackets after function execution

What is the purpose/ how does it work when declaring a function like:

myObj.request({myParam: null })[something](from, (error, res, body){
   //code
})

What is the behavior of this code? I don't get the meaning of [something] and the anonymous function that follows

i dont know the implementation details of your posted code so i can just guess:

myObj.request() will return an array/object of functions. With [something] you will select one of those functions and invoke it afterwards. As said, thats only guessing whats going on as you didnt provide any context. For example:

const myObj = {
  request: () => ({ 
    a: () => console.log('i am fn a'), 
    b: () => console.log('i am fn b'), 
  })
}

myObj.request()['a']() // console.logs 'i am fn a'

NOTE: for simplicity reasons i did not pass any arguments/callbacks to the functions. If you still have questions let me know and i'll update the answer

Javascript evaluates the expression inside square bracket, in your case the value for something and will executes the function with that name.

For example in your case

myObj.request({myParam: null })[something]

If the value of something is "get" as string. It will simply executes

myObj.request({myParam: null })["get"]

OR

myObj.request({myParam: null }).get

Its just like accessing a prperty inside an object, where myObj.request({myParam: null }) is the object and value for something is the property inside that object.

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