Home > Web Front-end > JS Tutorial > A brief discussion on JS functions and closures

A brief discussion on JS functions and closures

青灯夜游
Release: 2019-11-30 16:59:03
forward
2199 people have browsed it

Every time a function is declared, a scope will be generated. The outer scope cannot access the inner scope (hide the variables and functions inside), but the inner scope can access the outer scope. A very useful technique for hiding variables and functions.

A brief discussion on JS functions and closuresThe method based on scope hiding is called

Minimum authorization

or Minimum exposure principle. This principle means that in software design, necessary content should be exposed to a minimum and its content should be hidden, such as the API design of a certain module or object.

Hidden variables and functions can resolve conflicts between identifiers with the same name

. Conflicts can lead to accidental overwriting of variables. For example:

var a = 2;
function foo(){
  var a = 3;
  console.log(a);
}
foo();
console.log(a);
Copy after login

Although this technique can solve some problems, it is not ideal and will cause some additional problems. First, a named function foo() must be declared, which means foo The name itself "pollutes" the scope, and secondly, this function must be explicitly called through the function name foo() to run the code in it.


This would be more ideal if the function does not require a function name and can be run automatically. Fortunately, js provides a solution to these two problems at the same time - (IIFE) Immediately Invoked Function Expression -

Immediately execute the function

var a = 2;
(function foo(){
    var a = 3;
    console.log(a);
})()
console.log(a);
Copy after login
First of all

Immediate execution of the function

will not be treated as a function declaration but is treated as a function expression .

Distinguish between function declaration and function expression:

See whether function is the first word in the declaration. If it is the first word, it is a function declaration, otherwise it is a function expression. The function " (function " is executed immediately, not " function ", so it is a function expression.

Between function declaration and function expressionThe most important difference is where their name identifiers will be bound The function name declared by the function will be bound in the current scope .If you create a function declaration in the global scope, you can access the function name and execute it in the global scope. The function name of the function expression will be bound to its own function, not the current scope. For example You create a function expression globally. If you directly execute the function name of the function expression you created, an error will be reported because there is no such identifier in the current scope, and you access this function in the scope inside the function expression. name will return a reference to this function.

Scope closure, well, the two words closure are a bit difficult to understand, (you can imagine that a package is closed , there are some mysterious things hidden in it) The definition of closure says this: When a function can remember and access the scope in which it is located, a closure is generated, even if the function is executed outside the current scope.

for instance (English, haha).

function foo() {
    var a = 2;
    function bar() {
        console.log(a);
    }
    bar();
}
foo();
Copy after login

The above code bar() can access variables in the external scope. According to the above definition, is this a closure? Technically Maybe it is, but what we understand is that the scope searches for variables in the current scope. If it is not found, it will continue to search upwards. If it is found, it will return. If it is not found, it will continue to search until the global scope. -- And these are the closures part. The function bar() has a closure that covers the scope of foo().

function foo(){    var a  = 2;    function bar (){
        console.log(a);
    }    return bar;
}var baz = foo();
baz();
Copy after login

The above code shows the closure better.

The bar() function is defined when Executed outside the scope (executed in the global scope at this time). After the foo() function is executed, we usually expect the entire internal scope of foo() to be destroyed, because we know that the engine has a

garbage collector

Used to release unused memory space. Since foo() has been executed, it seems that the content will not be used anymore, so it is natural to consider alignment for recycling. After recycling, it means that the functions and variables inside cannot be accessed. .After foo() is executed, the baz variable stores a reference to the bar function. When executing baz, which is the bar function, console.log(a). People who do not understand closures may think that an error will be reported. In fact, 2 is printed. ;???What?Isn’t the foo() function scope destroyed after execution? How can you still access the a variable? -- This is a closure.

当foo()执行后,bar函数被返回全局作用域下,但是bar函数还保留着当时的词法作用域(当时写代码是的顺序就已经定义了作用域,这个作用域叫词法作用域--外面函数套着里面的函数的那种)甚至直到全局作用域。所以bar还留有foo()函数的引用。使得foo()函数没有被回收。

闭包可以说不出不在,只是你没有发现认出他。在定时器,事件监听器,ajax请求,跨窗口通信或者任何其他的异步(或者同步)任务中,只要使用了回调函数,实际上就是使用闭包。

for instance

function wait(message) {
    setTimeout(function timer() {
        console.log(message);
    }, 1000);
}
wait("hello");
Copy after login

在上面的代码中将一个内部函数(名为timer)传递给setTimerout(...).timer具有涵盖wait(...)的作用域的闭包。因此还保有对变量message的引用。wait()执行1000毫秒后,它的内部作用域不会消失,timer函数依然保有wait()作用域的闭包。

而闭包和立即执行函数息息相关。

循环和闭包

for(var i = 1; i <= 5; i++){
    setTimeout(function timer(){
        console.log(i);
    },i*1000);
}
Copy after login

上面代码我们以为输出的会是1-5,可事实上输出的是5个6,这是为啥啊 -- 闭包啊。

延迟函数的回调会在循环结束时执行。事实上,当定时器运行时即使每个迭代的是setTimerout(...,0),所有的回调函数依然是循环结束后才会执行。我猜是跟js执行机制有关系吧。至于为什么都是6. 因为即使5个函数是在各个迭代中分别定义的,但是他们又被封闭在一个共享的全局作用域中因此实际上只有一个i.而怎么解决呢,立即执行函数来了!!!

for (var i = 1; i <= 5; i++) {
    (function (i) {
        setTimeout(function timer() {
            console.log(i);
        }, i * 1000);
    })(i)

}
Copy after login

打印出来1,2,3,4,5了欧,这回是你想要的数了。解释一下,5次循环创建了5个立即执行函数,这5个函数的作用域都不相同,立即函数接收的参数是当前循环的i.所以当timer执行时访问的就是自己立即执行函数对应的作用域。也就是说5个timer函数分别对应5个作用域,每个作用域保存的变量i都不同,解决啦!!!

你懂闭包了吗?

js执行机制

JavaScript语言的一大特点就是单线程,也就是说,同一个时间只能做一件事。那么,为什么JavaScript不能有多个线程呢?这样能提高效率啊。JavaScript的单线程,与它的用途有关。作为浏览器脚本语言,JavaScript的主要用途是与用户互动,以及操作DOM。这决定了它只能是单线程,否则会带来很复杂的同步问题。比如,假定JavaScript同时有两个线程,一个线程在某个DOM节点上添加内容,另一个线程删除了这个节点,这时浏览器应该以哪个线程为准所以,为了避免复杂性,从一诞生,JavaScript就是单线程,这已经成了这门语言的核心特征,将来也不会改变。

单线程就意味着,所有任务需要排队,前一个任务结束,才会执行后一个任务。如果前一个任务耗时很长,后一个任务就不得不一直等着。JavaScript语言的设计者意识到这个问题,将所有任务分成两种,一种是同步任务(synchronous),另一种是异步任务(asynchronous)。同步任务指的是,在主线程上排队执行的任务,只有前一个任务执行完毕,才能执行后一个任务;异步任务指的是,不进入主线程、而进入"任务队列"(task queue)的任务,只有"任务队列"通知主线程,某个异步任务可以执行了,该任务才会进入主线程执行。

主线程从"任务队列"中读取事件,这个过程是循环不断的,所以整个的这种运行机制又称为Event Loop(事件循环)。只要主线程空了,就会去读取"任务队列",这就是JavaScript的运行机制。

哪些语句会放入异步任务队列及放入时机一般来说,有以下四种会放入异步任务队列:setTimeout 和 setlnterval  ,DOM事件,ES6中的Promise,Ajax异步请求

 本文来自 js教程 栏目,欢迎学习!

The above is the detailed content of A brief discussion on JS functions and closures. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:cnblogs.com
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