Home > Web Front-end > JS Tutorial > body text

Explanation of promotion and closure of js functions and variables

小云云
Release: 2018-03-14 10:24:30
Original
1470 people have browsed it

This article mainly shares two important knowledge points with you, the promotion of functions and variables and the detailed explanation of the principle and usage of closures. I hope it can help everyone.

Promotion of functions and variables

Principle: The declaration of functions and variables will be promoted to the top of the function.
Result: Both variables and functions support trial first and then declaration
Case:

//变量提升x = 5; 
// 变量 x 设置为 5alert(x);var x; 
// 声明 x//函数提升print(5); 
//调用函数function print(y) 
{ //声明函数    return y * y;}
Copy after login

Closure

Principle : Nest another function within the function (the other function is a closure)
Result:

  1. There is no static variable in js, you can Local variables declared within a function are used as local variables

  2. How to ensure that local variables are only called once? You can use variable assignment, that is, the outermost layer is called for the first time. Function, all subsequent calls to closures

  3. can prevent other functions from modifying them (other functions can modify global variables at will)

Case:

function count() 
{    var counter = 0;        
return function ()     
{return counter += 1;}}
var add= count();add();
add();//值为二
Copy after login

Related recommendations:

Detailed example code of how to determine the existence of functions and variables in JavaScript

Summary of basic JavaScript knowledge (10) Closures and immediate execution functions

Closures in JavaScript

The above is the detailed content of Explanation of promotion and closure of js functions and variables. For more information, please follow other related articles on the PHP Chinese website!

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