Let your JavaScript function have memory function and reduce the use of global variables

Source: Internet
Author: User

Consider the following scenario: if we need to draw a circle on the interface, the initial interface is blank, when the mouse moves, the circle needs to follow the mouse movement, the current position of the mouse is the center. Our implementation is: If the interface is not drawing a circle, then create a new one, if it already exists, directly update its location. This avoids the overhead of first destroying and then creating.

var circle = null;function Drawcircle (position) {if (circle = = null) {circle = GUI. Create (position);//creates 1 round}else{circle.updatepositon (position);//update the position of the Circle}}


There is no problem with this code, except that the global variable circle is introduced, and in fact Circle is only used in the Drawcircle () function. It is said that in order to achieve if-else judgment, we have to use global variables. Is there any way that the function can have a memory function that remembers whether a circle was created before. In that case, we don't have to use global variables.

var drawcircle = function (position) {var circle = null;function Innerfunc (position) {if (circle = = null) {circle = GUI. Create (position);} Else{circle.updatepositon (position);}} return innerfunc;} ();


This code can correctly implement the required functionality, and does not introduce unnecessary global variables.

var drawcircle = function (position) {} ();

This code defines 1 scopes, and the variables and functions defined inside the curly braces are invisible to the outside. And the code inside the curly braces executes immediately, assigning Innerfunc to the Drawcircle function before the code is finished. In this way, you can narrow the scope of the variable.  

Let your JavaScript function have memory function and reduce the use of global variables

Related Article

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.