closure
Standard: A function is defined inside a function. The inner function can use an external variable that cannot be cleaned
- demo
let yasso = {
q: function () {
let count = 0
return function () {
count ++
console.log( count)
if (count == 3) {
alert('hasaki')
count = 0
} else {
alert('hasai')
}
}
}
}
let q = yasso.q()
q();
q();
q();
Copy the code
When q is defined, JS finds the result of the yasso.q method, which returns a function, and q is temporarily bound to that function, which in turn uses its external variable count, so the value of count is saved.
If we find yasso.q() three times that count is 1 each time because count is redefined to be 0 each time
Garbage collection mechanism
- Mark clear
When a variable enters the environment, for example, declaring a variable in a function, the variable is marked as “entering the environment.” Logically, the memory occupied by entering the environment variables can never be freed, because they may be used whenever the execution flow enters the corresponding environment. When a variable leaves the environment, it is marked as “out of the environment”.
- Reference counting
When a value is referenced once, its count is +1. When a value is overwritten or deleted once, its count is -1. When its count reaches 0, it is cleared
Scope and scope chain
[pic1.zhimg.com/v2-6c734348…].
var value = 1;
function foo() {
console.log(value);
}
function bar() {
var value = 2; foo();
}
bar();
Copy the code