JS's closure and its cost

Source: Internet
Author: User
Tags object closure modify variable scope access

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.



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.