Home > Web Front-end > JS Tutorial > Javascript closure usage example analysis_javascript skills

Javascript closure usage example analysis_javascript skills

WBOY
Release: 2016-05-16 16:18:24
Original
1134 people have browsed it

This article analyzes the concept and usage of Javascript closures with examples. Share it with everyone for your reference. The details are as follows:

When it comes to closures, everyone must have heard of them. Here is my simple understanding.
To be honest, there are not many scenarios where closures are actually written manually in daily work, but the third-party frameworks and components used in the project more or less use closures.
Therefore, it is very necessary to understand closures. Haha...

1. What is closure

In short, it is a function that can read the internal variables of other functions.
Due to the characteristics of JS variable scope, internal variables cannot be accessed from the outside, but external variables can be accessed from the inside.

2. Usage scenarios

1. Implement private members.
2. Protect the namespace and avoid polluting global variables.
3. Cache variables.

Let’s look at an example of encapsulation first:

Copy code The code is as follows:
var person = function () {
//The scope of the variable is inside the function and cannot be accessed from outside
var name = "default";

return {
          getName: function () {
              return name;
},
setName: function (newName) {
              name = newName;
}
}
}();

console.log(person.name); // Direct access, the result is: undefined
console.log(person.getName()); // The result is: default
console.log(person.setName("langjt"));
console.log(person.getName()); // The result is: langjt

Look at the commonly used closures in loops to solve the problem of referencing external variables:

Copy code The code is as follows:
var aLi = document.getElementsByTagName('li');
for (var i=0, len=aLi.length; i aLi[i].onclick = function() {
alert(i); // No matter which
  • element is clicked, the value that pops up is len, indicating that the value of i here is the same as the value of i printed after for.
    };
    }

  • After using closure:
    Copy code The code is as follows:
    var aLi = document.getElementsByTagName('li');
    for (var i=0, len=aLi.length; i aLi[i].onclick = (function(i) {
    Return function() {
    alert(i); // Click the
  • element at this time, and the corresponding subscript will pop up.
    }
    })(i);
    }
  • 3. Precautions

    1. Memory leak

    Since closures cause all variables in the function to be stored in memory, which consumes a lot of memory, closures cannot be abused, otherwise it will cause performance problems on the web page.
    For example:

    Copy code The code is as follows:
    function foo() {
    var oDiv = document.getElementById(‘J_DIV’);
    var id = oDiv.id;
    oDiv.onclick = function() {
    // alert(oDiv.id); There is a circular reference here, and oDiv is still in the memory after the IE low version page is closed. So cache primitive types instead of objects whenever possible.
    ​​ alert(id);
    };
    oDiv = null;
    }

    2. Variable naming

    If the variable name of the internal function and the variable name of the external function are the same, then the internal function can no longer point to the variable with the same name of the external function.
    For example:

    Copy code The code is as follows:
    function foo(num) {
    return function(num) {
    console.log(num);
    }
    }
    var f = new foo(9);
    f(); // undefined

    En fait, l'usage ci-dessus, le terme professionnel est appelé currying de fonction, consiste à transformer une fonction qui accepte plusieurs paramètres en une fonction qui accepte un seul paramètre (le premier paramètre de la fonction d'origine), et renvoie les paramètres restants. . Nouvelle technologie de fonction qui prend des paramètres et renvoie un résultat. Essentiellement, il profite également de la fonction de mise en cache des fermetures, telles que :

    Copier le code Le code est le suivant :
    var adder = function(num) {
    Fonction de retour (y) {
              return num y;
    };
    };

    var inc = additionneur(1);
    var déc = additionneur(-1);
    //inc, dec sont maintenant deux nouvelles fonctions, leur fonction est de convertir la valeur du paramètre transmis (/‐)1
    alerte(inc(99));//100
    alert(dec(101));//100
    alert(adder(100)(2));//102
    alerte(adder(2)(100));//102

    Un autre exemple est le code source seaJS d'Ali Yubo :

    Copier le code Le code est le suivant :
    /**
     * util-lang.js - L'amélioration minimale du langage
     */
    fonction isType(type) {
    fonction de retour (obj) {
    Retour {}.toString.call(obj) == "[objet " type "]"
    >
    >

    var isObject = isType("Object");
    var isString = isType("String");

    J'espère que cet article sera utile à la conception de la programmation JavaScript de chacun.

    Related labels:
    source:php.cn
    Statement of this Website
    The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
    Popular Tutorials
    More>
    Latest Downloads
    More>
    Web Effects
    Website Source Code
    Website Materials
    Front End Template