• JS event loop mechanism

console.log('one')
setTimeout(function () {
    console.log('two')    
}, 0)
console.log('three')Copy the code

The output is

one
three
twoCopy the code

The key of this problem is the JS event loop mechanism, for asynchronous processing operations, JS has a password: synchronization first, asynchronous sideline, callback last.

The first console.log is executed synchronously and directly outputs one

When a setTimeout callback is encountered after execution (executed last), put setTimeout into the callback message queue to wait

Then console.log(‘three’) is executed synchronously, printing three directly, and then the callback queue executes two after all the synchronized messages are executed

  • Closures and scopes

function test() {
    var n = 4399;
    function add() {
        n++;
        console.log(n);
    }
    return {
        n: n,
        add: add
    }
}
var result = test(a); var result2 =test(a); result.add(); result.add(); console.log(result.n); result2.add();Copy the code

The output

4400
4401
4399
4400Copy the code

Var result = test(); var result2 = test(); var result = test()

Generation of closures: Closures are generated when function B is defined in function A and variables in function B are referenced in function A

var result = test() // Set the result attribute to {n:4399, add: add()} var result2 =test() // Set the result2 attribute to {n:4399, add: Add ()}result.add() // call result add(), execute n++, so n = 4399 + 1 Output 4401 console.log(result.n) // This is output result n value, output 4399, here is output object property return value, The closure result2.add() is not called // the add method of result2 is called, so n = 4399, so n = 4399 + 1 output 4400Copy the code

 

  • Scope chain title

var myObject = {
    foo: "bar",
    func: function() {
        var self = this;
        console.log(this.foo);
	console.log(self.foo);
	(function() {
	    console.log(this.foo);
	    console.log(self.foo);
	}());
    }
};
myObject.func();
Copy the code

The output

bar
bar
undefined
barCopy the code

This refers to a method or function that is called by it

Func is called by myObject, this refers to myObject, and output bar

2. Self points to myObject and prints bar

3, immediately execute the anonymous function expression called by window, this refers to window

The function cannot find self in this scope, so it looks up the scope chain for the self variable and finds self in the parent function that points to myObject