Home  >  Article  >  Web Front-end  >  Detailed explanation of must-have packages for JavaScript

Detailed explanation of must-have packages for JavaScript

php中世界最好的语言
php中世界最好的语言Original
2018-03-16 17:06:391744browse

This time I will bring you a detailed explanation of javascript, What are the precautions when using javascript, the following is a practical case, let’s take a look .

Closure, this name is so strange,
Let’s get back to the point, let’s talk about the variables of js functionScope
The following examples are all based on local variables

Accessing function external variables inside the function

demo1:
   var a = 100;    function get() {        console.log(a)    }    get();    // 运行结果:100

In the demo1 example, variable a is declared outside the function and can be called in the function get(). Call the get() function, The browser console will output 100, which is the value of a.

External access to variables declared within the function

demo2:
   function get() {        var a = 100;    }    get();    console.log(a);    //运行结果:ReferenceError: a is not defined

In the demo2 example, the variable a is declared in the function get(). After the function get() is executed, the variable a is called. In the control Station output: ReferenceError: a is not defined (a is not defined). It can be seen that variables declared within the function cannot be directly called outside the function.
Isn’t it possible to get the variables inside the function? Of course not. Closures come in handy at this time. Look at the following code:

   function get() {        var a = 100;        return function () {            return a;
        }
    }    var b = get();    console.log(b);    //运行结果:
    /* function () {
        return a;
    }*/
    console.log(b());    // 运行结果:100

The function get() returns a function. This function returns the variable you want to get, and then you can do it outside the function. Through get()(), you can get the value of the variable inside the function.

The above is the detailed content of Detailed explanation of must-have packages for JavaScript. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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