search
HomeWeb Front-endJS TutorialA brief discussion on JS functions and closures

A brief discussion on JS functions and closures

Nov 30, 2019 pm 04:58 PM
jsfunctionClosure

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);

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);
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();

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();

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");

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

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

循环和闭包

for(var i = 1; i <p>上面代码我们以为输出的会是1-5,可事实上输出的是5个6,这是为啥啊 -- 闭包啊。</p><p>延迟函数的回调会在循环结束时执行。事实上,当定时器运行时即使每个迭代的是setTimerout(...,0),所有的回调函数依然是循环结束后才会执行。我猜是跟js执行机制有关系吧。至于为什么都是6. 因为即使5个函数是在各个迭代中分别定义的,但是他们又被封闭在一个共享的全局作用域中因此实际上只有一个i.而怎么解决呢,立即执行函数来了!!!</p><pre class="brush:php;toolbar:false">for (var i = 1; i <p>打印出来1,2,3,4,5了欧,这回是你想要的数了。解释一下,5次循环创建了5个立即执行函数,这5个函数的作用域都不相同,立即函数接收的参数是当前循环的i.所以当timer执行时访问的就是自己立即执行函数对应的作用域。也就是说5个timer函数分别对应5个作用域,每个作用域保存的变量i都不同,解决啦!!!</p><p>你懂闭包了吗?</p><p><strong>js执行机制</strong></p><p><span class="bjh-p">JavaScript语言的一大特点就是单线程,也就是说,<span class="bjh-strong">同一个时间只能做一件事。那么,为什么JavaScript不能有多个线程呢?这样能提高效率啊。</span></span><span class="bjh-p">JavaScript的单线程,与它的用途有关。作为浏览器脚本语言,JavaScript的主要用途是与用户互动,以及操作DOM。这决定了它只能是单线程,否则会带来很复杂的同步问题。比如,假定JavaScript同时有两个线程,一个线程在某个DOM节点上添加内容,另一个线程删除了这个节点,这时浏览器应该以哪个线程为准</span><span class="bjh-p">所以,为了避免复杂性,从一诞生,JavaScript就是单线程,这已经成了这门语言的核心特征,将来也不会改变。</span></p><p><span class="bjh-p">单线程就意味着,所有任务需要排队,前一个任务结束,才会执行后一个任务。如果前一个任务耗时很长,后一个任务就不得不一直等着。JavaScript语言的设计者意识到这个问题,将所有任务分成两种,<span class="bjh-strong">一种是同步任务(synchronous),另一种是异步任务(asynchronous)。同步任务指的是,在主线程上排队执行的任务,只有前一个任务执行完毕,才能执行后一个任务;异步任务指的是,不进入主线程、而进入"任务队列"(task queue)的任务,只有"任务队列"通知主线程,某个异步任务可以执行了,该任务才会进入主线程执行。</span></span></p><p><span class="bjh-p">主线程从"任务队列"中读取事件,这个过程是循环不断的,所以整个的这种运行机制又称为Event Loop(事件循环)。只要主线程空了,就会去读取"任务队列",这就是JavaScript的运行机制。</span></p><p><span class="bjh-h3">哪些语句会放入异步任务队列及放入时机</span><span class="bjh-p">一般来说,有以下四种会放入异步任务队列:</span><span class="bjh-ol"><span class="bjh-li"><span class="bjh-p">setTimeout 和 setlnterval  ,<span class="bjh-li"><span class="bjh-p">DOM事件,<span class="bjh-li"><span class="bjh-p">ES6中的Promise,<span class="bjh-li"><span class="bjh-p">Ajax异步请求</span></span></span></span></span></span></span></span></span></p><p> 本文来自 <a href="https://www.php.cn/js-tutorial.html" target="_blank">js教程</a> 栏目,欢迎学习!</p>

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!

Statement
This article is reproduced at:cnblogs. If there is any infringement, please contact admin@php.cn delete
Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version