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.