Global and Local and Private Functions (Javascript)

前端 未结 6 581
情深已故
情深已故 2021-01-18 06:46

I am currently reading a book on Javascript by Pragmatic, and I\'m confused about one thing. They have a section on how to make variables global, local, or private.

6条回答
  •  逝去的感伤
    2021-01-18 07:08

    Private variables only make sense when you are constructing objects. The typical prototype pattern has you add any necessary variables and helper functions as properties of the instance of the object and/or its prototype, but this has the disadvantage of making them visible to anyone with access to the object. To avoid this, there is an alternative pattern where the variables are local variables of the constructor, and all the methods are declared in the constructor scope and only the public ones are assigned as actual properties of the object.

提交回复
热议问题