Javascript function as a parameter to another function?

后端 未结 7 1083
执念已碎
执念已碎 2021-01-31 06:17

I\'m learning lots of javascript these days, and one of the things I\'m not quite understanding is passing functions as parameters to other functions. I get the concept

7条回答
  •  隐瞒了意图╮
    2021-01-31 06:31

    Passing a function as a parameter to another function is useful in a number of situations. The simplest is a function like setTimeout, which takes a function and a time and after that time has passed will execute that function. This is useful if you want to do something later. Obviously, if you called the function itself and passed the result in to the setTimeout function, it would have already happened and wouldn't happen later.

    Another situation this is nice is when you want to do some sort of setup and teardown before and after executing some blocks of code. Recently I had a situation where I needed to destroy a jQuery UI accordion, do some stuff, and then recreate the accordion. The stuff I needed to do took a number of different forms, so I wrote a function called doWithoutAccordion(stuffToDo). I could pass in a function that got executed in between the teardown and the setup of the accordion.

提交回复
热议问题