📜 ⬆️ ⬇️

A closure in java script for the uninitiated

My programmers had a task: to highlight the thumbnail of the displayed image in the photo gallery with the active image. The task seems to be trivial, but they have caused some gag when solving. I want to say right away that they didn’t have the best JS ownership.
In general, few people truly know this language and do not confuse it with the principles of the DOM document.

What was the problem ...
1. That at first they solved it with recursion :)
2. The second attempt to solve led to the introduction of a global variable, which I do not think is good
3. Contamination of the general code with similar small functions instead of using the object approach

When I was a programmer, I wrote a small frame for the demonstration. Here he is:
')
<script type = "text / javascript" >


function MainMenu () {

var OldImage;

this .getOldImage = function () { return OldImage; }
this .setOldImage = function (img) {OldImage = img;}
this .chgImage = function (obj, newImage) {
if (newImage! = null ) {
this .setOldImage (obj.src);
obj.src = '/ images /' + newImage;
} else {
obj.src = this .getOldImage ();
}
}

}

var Menu = new MainMenu ();

</ script> This code was highlighted with Source Code Highlighter .


Call it like this:

<img src = "/images/home.gif" width = "88" height = "23" alt = "" onmouseover = "Menu.chgImage (this, 'home_over.gif')" onmouseout = "Menu.chgImage (this ) » > * This source code was highlighted with Source Code Highlighter .


What it gave us:

1. We do not use recursion. By this we save computer resources. In client machines, they are not rubber, contrary to the statements
2. We have not introduced a global variable, which in large systems is inconvenient for objective reasons
3. Third, we made a universal object. He encapsulated data!

Beginners, please understand and understand. This option is made specifically easier than we implemented.

We create a local variable in the function body. Then we capture this variable by the method of this function (this is a class, more precisely, a prototype). As a result, we get a clever trick. When exiting the function itself, the data in it was remembered.

In fact, there is enough material on this issue on the net. This trick is far from new. But you need to remind about it "fathers" and teach beginners.

Source: https://habr.com/ru/post/37236/


All Articles