javascript closure advantages?

前端 未结 4 1187
别那么骄傲
别那么骄傲 2020-12-24 03:19

Whats the main purpose of Closures in JS. Is it just used for public and private variables? or is there something else that I missed. I am trying to unders

4条回答
  •  天涯浪人
    2020-12-24 03:39

    Closures are necessary in javascript due to the fact that most API's that require callback functions (for instance, an "onclick" function) do not provide other mechanisms to send parameters to those callback functions (or to explicitly set the "this" pointer). Instead, you need to use closures to allow the callback to access variables in the "parent" function.

    I personally wish that they weren't necessary, since they can be hard to understand, make for hard to read code (it's not always clear what exactly is in scope), and make for weird bugs. Instead I wish there was a standard for callbacks that allowed you to send parameters, etc. But I accept that I am in the minority in this view.

提交回复
热议问题