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