javascript closure advantages?

前端 未结 4 1205
别那么骄傲
别那么骄傲 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:31

    As we know, the variables that are defined in functions, have local scope. We can't access them from outside of the function.

    Problem 1:

    local variables are created when the function is called and they will be destroyed when the function's task is finished. It means local variables have shorter life time than global variables. We may use global variables to overcome that issue.

    Global variables are available when the program starts and are destroyed when it ends. They are also available throughout the program.

    Problem 2:

    Since global variables are accessible throughout the program, they are prone to change from everywhere.

    What do we want?

    We want to have data persistence + data encapsulation.

    We can achieve them by using Closures. By using a closure we can have private variables that are available even after a function's task is finished.

提交回复
热议问题