Javascript closure usage example analysis_javascript skills
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:
//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:
for (var i=0, len=aLi.length; i
alert(i); // No matter which
};
}
After using closure:
for (var i=0, len=aLi.length; i
Return function() {
alert(i); // Click the
}
})(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:
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:
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 :
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 :
* 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.

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



In C++, a closure is a lambda expression that can access external variables. To create a closure, capture the outer variable in the lambda expression. Closures provide advantages such as reusability, information hiding, and delayed evaluation. They are useful in real-world situations such as event handlers, where the closure can still access the outer variables even if they are destroyed.

C++ Lambda expressions support closures, which save function scope variables and make them accessible to functions. The syntax is [capture-list](parameters)->return-type{function-body}. capture-list defines the variables to capture. You can use [=] to capture all local variables by value, [&] to capture all local variables by reference, or [variable1, variable2,...] to capture specific variables. Lambda expressions can only access captured variables but cannot modify the original value.

A closure is a nested function that can access variables in the scope of the outer function. Its advantages include data encapsulation, state retention, and flexibility. Disadvantages include memory consumption, performance impact, and debugging complexity. Additionally, closures can create anonymous functions and pass them to other functions as callbacks or arguments.

Go language function closures play a vital role in unit testing: Capturing values: Closures can access variables in the outer scope, allowing test parameters to be captured and reused in nested functions. Simplify test code: By capturing values, closures simplify test code by eliminating the need to repeatedly set parameters for each loop. Improve readability: Use closures to organize test logic, making test code clearer and easier to read.

Yes, code simplicity and readability can be optimized through chained calls and closures: chained calls link function calls into a fluent interface. Closures create reusable blocks of code and access variables outside functions.

The impact of function pointers and closures on Go performance is as follows: Function pointers: Slightly slower than direct calls, but improves readability and reusability. Closures: Typically slower, but encapsulate data and behavior. Practical case: Function pointers can optimize sorting algorithms, and closures can create event handlers, but they will bring performance losses.

Closures in Java allow inner functions to access outer scope variables even if the outer function has exited. Implemented through anonymous inner classes, the inner class holds a reference to the outer class and keeps the outer variables active. Closures increase code flexibility, but you need to be aware of the risk of memory leaks because references to external variables by anonymous inner classes keep those variables alive.

The use of POST requests in PHP is a common operation in website development. Data can be sent to the server through POST requests, such as form data, user information, etc. Proper use of POST requests can ensure data security and accuracy. The following will introduce the correct usage of POST requests in PHP and provide specific code examples. 1. Basic principles of POST requests in PHP In PHP, the data submitted through the POST method can be obtained by using the $_POST global variable. The POST method converts the form number into
