Took part in Baidu Internship interview, the interviewer asked a question about JS closure. Here's a quick look at the closure and its cost.
Closures have many interesting uses, and the two features of JavaScript make it so interesting: 1. A function is an object that is equal to an array, object. 2. JavaScript variable scope range. The JavaScript Authority Guide has an in-depth explanation of these two points.
A well-known use of closures is the realization of object-oriented access control. That is, C + +, C #, Java, such as object-oriented private, public access control. Look at a sample code first
The above code is very simple, just put data member A's accessor (setter/getter), in the constructor. A using the Var declaration, there is no direct access to a. Both Get_a and set_a use this to associate the two functions with the class object and are visible outside.
The above method is very skillful, but I have never done so, Microsoft's ajax.net also did not use the closure to achieve access control. The reason is that it takes up more memory, and here's why it takes up more memory.
First, we use a prototype (prototype) to define a class
From the results above, it can be seen that using prototype-defined classes, instantiated objects share the same method, and once the prototype changes, all objects are affected. While an object modifies its own method, the system performs copy on write, pointing the object to a new method without affecting other objects.
Take another look at the following paragraph:
As you can see from the results of the operation, the result of the closure is that each object has a separate method, even if the method between the objects is implemented identically. This can result in excess memory waste. Imagine how much memory would be wasted if a class that uses closures has many objects.