closure

First, scope exploration

Scope definition: a function in which variables (variables acting on context) and functions are in effect (can be accessed) nested within each other. The inside can access the outside, but the outside cannot access the inside

Outside do not access inside demo:

var a = 123; function test() { var b = 123; } test(); // document.write(b);Copy the code

Inside can access the outside demo:

var a = 123; function test() { var b = 0; function demo() { var c = 234; console.log(b); //0 console.log(a); //123 } demo(); // document.write(c); } test();Copy the code

Second, JS run trilogy

JS force: single thread; Interpretive language

Syntax analysis, scanning throughout —–> precompile ——-> Explain execution

1. The precompiled

The introduction of the demo

var a = 123; console.log(a); //123 console.log(a); var a = 123; //undefinedCopy the code

Function declaration improves overall

function test(){}
Copy the code

Variable declaration promotion

var a; document.write(a); a = 123; //var a = 123; Equivalent to var a; a = 123Copy the code

Problems that can’t be solved in two words

console.log(a);
function a(a){
    var a = 234;
    var a = function(){ 
    }
    a();
}
var a = 123;
Copy the code

Precompilation prelude:

Imply Global: Any variable that is assigned an undeclared value belongs to the global object Window.

function test(){ var a = b =1; } test();} test(); //var a = 123; Declare a and assign console.log(window.a); console.log(window.b);Copy the code

2. All declared global variables are window properties. Window is the global field; Window is the global:

var a = 123; console.log(a); //---->window.a = 123; Window {a: 123 // equivalent}Copy the code

Classic demo

function test() { var a = b = 123; } test(); console.log(window.b); //undefined, local, not global console.log(a);Copy the code

Declaring local variables is not demo

function test(){
    var b = 123;
}
test();
console.log(window.b);
console.log(b);
Copy the code

Precompiled tetralogy

Precompilation occurs just before the function is executed

1. Create the Activation object execution context 2. Find the parameter and variable declarations and use the variable and parameter names as the AO property names with the value undefined 3. 4. Find the function declaration inside the function body, and assign the value to the function body

Example 1

function fn(a){ console.log(a); // function a(){} var a = 123; Var a=123; console.log(a); // 123 function a(){} console.log(a); Var b=function(){} console.log(b); var b=function(){} console.log(b); // function(){} function d(){} } fn(1);Copy the code

Example 2

function test(a,b) { console.log(a); c = 0; var c; a = 3; b = 2; console.log(b); function b() {} function d() {} console.log(b); } test(1); / / the answer 122Copy the code

Example 3

function test(a, b) {
    console.log(a);
    console.log(b);
    var b = 234;
    console.log(b);
    a = 123;
    console.log(a);
    function a(){}
    var a;
    b = 234;
    var b = function () {}
    console.log(a);
    console.log(b);
}
test();
Copy the code

Precompilation occurs not only in the function system, but also globally, which generates a GO object with a different name and the same steps. The window is the GO

// GO // GO{ // b : 123; // } function test(){ var a = b = 123; console.log(window.b); } test(); //AO {//A :undefiend // does not work with B //} // But there is no A in the defiendCopy the code

// GO{ // test:function(){… } // } console.log(test); function test(test) { console.log(test); var test = 234; console.log(test); function test() { } } test(1); var test = 123; // AO{// //test at the moment before execution // // GO,

Difficulty is 1:Copy the code

// GO{ // global : undefined—->100 // fn : function (){… } // } var global = 100; function fn(){ console.log(global); }} fn();}} fn();

Difficulty of 2:Copy the code

global = 100; function fn(){ console.log(global); global = 200; console.log(global); var global = 300; } fn(); var global; // global:undefined; // global:undefined; //

The difficulty of 3Copy the code

} function test() {console.log(b);} function test() {console.log(b);} function test() {console.log(b); //undefined if(a) { var b = 100; } console.log(b); //undefined because c = 234; // Imply the global variable console.log(c); //234 } var a; test(); // AO{ // b : undefined // } a = 10; console.log(c); / / 234

Baidu questionsCopy the code

function bar(){ return foo; foo = 10; function foo(){ } var foo = 11; } console.log(bar()); // answer: function foo(){}return

Baidu questionsCopy the code

console.log(bar()); function bar(){ foo = 10; function foo(){} var foo = 11; return foo; //return = 11}

** Variable declarations are promoted **Copy the code

console.log(b); //undefined var b = function () { }

The top difficultyCopy the code

// GO{// a: undefined, // demo: function () {// then a:100; At the moment before demo execution, AO // f :123 //} a = 100; function demo(e){ function e() {} arguments[0] = 2; console.log(e); If (a) {if(a) = 123; Function c() {}} var c; a = 10; var a; console.log(b); //undefined f = 123; // if there is nothing in AO, throw it to GO to hint at the global variable console.log(c); //func unde console.log(a); //10 } var a; AO {/ / parameter e: undefined 1 — — — — — – > > function e () {} – > 2 b: c: undefined undefined – > (function () {}).a: undefined—>10 } demo(1); // GO console.log(a); //100 console.log(f); / / 123

JiCheng topicCopy the code

//typeof(null); —-object var str = false + 1; document.write(str); //1 var demo = false == 1; document.write(demo); / / false if (typeof && – true (a) + (+ undefined) + “”) {document. Write (‘ solid ‘); } / / “undefined” && – 1 + “” +” NAN “type string if (11 +” 11 “* 2 = = 33) {document. Write (‘ solid ‘); }!!!!!” “+!!!!!” “-!!!!! False | | document. Write (‘ what do you think can print, you are pig ‘); / / string true / / “” “” Spaces empty string of true/false “+ false false = = 1 stopped / / 1 | | (omitted)

CSS display attributes display: None /block/inline-block/inline...... 2. What are the list-style attributes of the CSS?Copy the code
   

   

Parallel layout, evenly split parent level, and no spacing // two-column layout 4. Use CSS HTML triangle 5. Center horizontally and vertically 6. Write window.foo

(window.foo || window.foo = 'bar'); / / such an error, such calculations or first, priority (window. The foo | | (window. Foo = 'bar')); // First look at the parentheses, barCopy the code

3. Fine solution of scope

[[scope]]: Every javascript function is an object. Some properties of the object are accessible to us, but others are not. These properties are only accessible to the javascript engine, and [[scope]] is one of them. [[scope]] refers to what we call a scope, which stores a collection of run-time contexts. Scope chain: a collection of execution-time context objects stored in [[scope]]. This collection is linked in a chain called scope chain. 3. Runtime context: When a function executes, an internal object AO called the runtime context is created. An execution-time context defines the context in which a function is executed. Each time a function is executed, the corresponding execution context is unique. Therefore, multiple calls to a function result in the creation of multiple execution contexts, which are destroyed when the function completes execution. Find variables: Look down from the top of the scope chain.

var a = 100; function test() { var a = 234; console.log(a); } test();} test();Copy the code

Small example

function a(){
    function b() {
        var b = 234;
    }
    var a = 123;
    b();
    console.log(a);
}
var glob = 100;
a();
// a defined a.[[scope]]---> 0:GO{}
// a.doing   a.[[scope]]---> 0:AO{}
//                           1:GO{}
Copy the code

Two AO are references, pointing to the same room

function a(){
    function b() {
        var bb = 234;
        aa = 0;
    }
    var a = 123;
    b();
    console.log(aa);
}
var glob = 100;
a();
Copy the code

example

function a() { function b() { function c(){ } c(); } b(); } a(); a defined a.[[scope]] ---> 0:GO a doing a.[[scope]] ---> 0 : aAO 1 : GO b defined b.[[scope]] ---> 0:aAO 1:GO b doing b.[[scope]] ---> 0:bAO 1:aAO 2:GO c defind c.[[scope]] ---> 0:bAO 1:aAO  2:GO c doing c.[[scope]] ---> 0:cAO 1:bAO 2:aAO 3:GOCopy the code

Fourth, the closure

1. Definition:

When an internal function is saved externally, a closure is generated. Closures can cause the original scope chain to not be released, causing memory leaks

2. Closure examples

Example 1

function a() { function b(){ var b = 234; console.log(aaa); //123 } var aaa = 123; return b; } var glob = 100; var demo = a(); demo();Copy the code

Example 2

function a() { var num = 100; function b() { num ++; console.log(num); } return b; } var demo = a(); demo(); //101 demo(); / / 102Copy the code

3. What closures do

Implement the public variable eg: function accumulator, previously dependent on external variables

function add() {
    var count = 0;
    function demo(){
        count++;
        console.log(count);
    }
    return demo;
}
var counter = add();
counter();
counter();
counter();
counter();
counter();
Copy the code

You can cache eg: Eater

function test() { var num = 100; function a(){ num++; console.log(num); } // a defined a.[[scope]] 0 : testAO // 1 : GO function b(){ num--; console.log(num); } // b defined b.[[scope]] 0 : testAO // 1 : GO return [a,b]; } var MyArr = test(); MyArr[0](); // a doing a.[[scope]] 0 : aAO // 1 : testAO * // 2. GO MyArr[1](); // b doing b.[[scope]] 0: bAO // 1: testAO * // 2Copy the code

Cache Demo

function eater() {
    var food = "";
    var obj = {
        eat : function (){
            console.log("i am eating " + food);
            food = "";
        },
        push : function(myFood) {
            food = myFood;
        }
    }
    return obj;
}
var eater1 = eater();
eater1.push('banana');
eater1.eat();
Copy the code

You can encapsulate and privatize attributes eg: Person();

Modular development to prevent contamination of global variables

Function declaration && function expression difference

4. Closure prevention

Closures can cause multiple executing functions to share a common variable, and you should try to prevent this from happening unless you have a special need

Execute the function immediately

Definition: This type of function is undeclared and is released after a single execution. Good for initialization

A function for the initialization function. Executing a function immediately and destroying it immediately is no different from a function

var num = (function (a, b, c){ var d = a + b + c; return d; } (1, 2, 3))Copy the code

There are two ways to write the immediately executing function:

  1. (function (){}()); The W3C recommends the first
  2. (function (){})();

The phenomenon of

Function test() {var a = 123; } (); Function test() {var a = 123; } test(); //test is an expressionCopy the code

Above, only expressions can be executed by executing symbols

function test() { var a = 123; }// function declaration 123; // function expression test(); Var test = function() {console.log('a'); var test = function() {console.log('a'); } (); Var test = function() {console.log('a'); var test = function() {console.log('a'); } var test = function() { console.log('a'); } (); + function test(){console.log('a'); } (); / / a minus sign, exclamation, not, (add on behalf of the positive and negative), &&, | | / / thriller (function test () {the console. The log (' a '); })() (function test { console.log('a'); }()) // This function name is automatically ignored because of the expression executed by the executed symbol (function () {console.log('a'); }()) // Execute functions immediately in many formsCopy the code

Immediately implement the function to explore the bottom of the blog – breadth or depth to see an article alibaba

function test(a,b,c,d) { console.log(a+b+c+d); } (1, 2, 3, 4); Function test(a,b,c,d) {console.log(a+b+c+d); function test(a,b,c,d) {console.log(a+b+c+d); } (1, 2, 3, 4);Copy the code

Key introduction examples:

function test () { var arr = []; For (var I = 0; i < 10; i++) { arr[i] = function () { document.write(i + ' '); } } return arr; } var myArr = test(); for(var j = 0; j < 10; j++){ myArr[j](); }Copy the code

Why is it 10 i++ why is it all 10

arr[i] = function () {
    document.write(i + ' ');
}
Copy the code

Document.write (I + “); document.write(I + “); I don’t do it until I call it, I don’t do it until I call it, and when I do it it’s all tens. Execution position! = Define position how to solve (the only way) ten small immediately execute function

function test () { var arr = []; For (var I = 0; i < 10; i++) { (function (j){ arr[j] = function () { document.write(j + " "); } }(i)); } return arr; } var myArr = test(); for(var j = 0; j < 10; j++){ myArr[j](); }// Print I is still 10, // execute now is read immediatelyCopy the code

Closure refinement

var demo; function test() { var abc = 100; function a(){ console.log(abc); } demo = a; } test(); demo(); // Save the inside to the outside, generate closureCopy the code

Alibaba pen test questions (UC mobile business group) recruitment questions

function test() {
    var liCollection = document.getElementsByTagName('li');
    for(var i  = 0; i < liCollection.length; i++){
        liCollection[i].onclick = function(){
            console.log(i);
        }
    }
}
test();
Copy the code
<! DOCTYPE html> <html> <head> <title>hehe</title> <style type="text/css"> *{ margin: 0; padding: 0; } ul{ list-style: none; } li:nth-of-type(2n){ background-color: red; } li:nth-of-type(2n+1){ background-color: green; } </style> </head> <body> <ul> <li>a</li> <li>a</li> <li>a</li> <li>a</li> </ul> <script type="text/javascript"> function test() { var liCollection = document.getElementsByTagName('li'); for(var i = 0; i < liCollection.length; i++){ (function(j){ liCollection[i].onclick = function(){ console.log(j); } }(i)) } } test(); </script> </body> </html>Copy the code

Pen test

var x = 1; if(function f() {}){ x += typeof f; } console.log(x); //1undefinedCopy the code