Make your javascript functions have the memory function, reduce the use of global variables, javascript global variables

Source: Internet
Author: User

Make your javascript functions have the memory function, reduce the use of global variables, javascript global variables

Consider the following scenario: if we need to draw a circle on the interface, the interface is blank at the beginning; when the mouse moves, the circle needs to follow the mouse, the current position of the mouse is the center of the circle. Our implementation scheme is: if there is no circle on the interface, a new one will be created; if there is already, the location will be updated directly. This avoids the overhead created after destruction.

Var circle = null; function drawCircle (position) {if (circle = null) {circle = GUI. create (position); // Create 1 circle} else {circle. updatePositon (position); // update the circle position }}


There is no problem with this Code. Apart from introducing the global variable circle, actually circle will only be used in the drawCircle () function. In other words, we have to use global variables to realize the if-else judgment. Is there any way to make the function have a memory function and remember whether circles have been created before. In this way, we do not need 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 correctly implements the required functions without introducing unnecessary global variables.

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

 

This Code defines a scope. Variables and Functions Defined inside braces are invisible to the outside. In addition, the code inside the braces is immediately executed. After the code is completed, the innerFunc is assigned to the drawCircle function. In this way, the scope of the variable can be reduced.

 

 

 

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.