Why are self-executing anonymous functions used in Javascript Module pattern?

前端 未结 3 2164
野性不改
野性不改 2020-12-31 17:01

In the module pattern in JavaScript \"Immediately-Invoked Function Expressions\" (also known as self-executing anonymous functions) are used as self executing functions that

3条回答
  •  北海茫月
    2020-12-31 17:24

    The privateness is because of closures. The "var privateVariable" is closed over by "PublicMethod", so only that function can access the variable because only it has it in its closure. It cannot be referenced by anything else and is "private"

    This happens not only in "Immediately-Invoked Function Expressions" but also in normal function calls. It is just a way to immediately create the closure when defining the module instead of doing it later when you call the outer function.

    Also see this post from Douglas Crockford himself: http://javascript.crockford.com/private.html

提交回复
热议问题