search
HomeWeb Front-endJS TutorialAdvanced front-end basics (6): Observe function call stacks, scope chains and closures in Chrome developer tools

In front-end development, there is a very important skill called breakpoint debugging.

In Chrome's developer tools, through breakpoint debugging, we can very conveniently observe the execution process of JavaScript step by step, and intuitively perceive the function call stack, scope chain, variable object, closure, this changes in key information. Therefore, breakpoint debugging plays a very important role in quickly locating code errors and quickly understanding the execution process of the code. This is also an essential advanced skill for our front-end developers.

Of course, if you don’t know enough about these basic concepts of JavaScript [execution context, variable objects, closures, this, etc.], it may be difficult to thoroughly master breakpoint debugging. But fortunately, in the previous articles, I have given a detailed overview of these concepts, so it should be relatively easy for everyone to master this skill.

In order to help everyone have a better understanding of this and closure, and because the definition of closure in the previous article is a bit biased, I will use closure-related examples in this article. Learn about breakpoint debugging so that everyone can make corrections in time. I admit my mistake here and misled everyone.


##1. Review of basic concepts

Functions are When execution is called, an execution context for the current function is created. During the creation phase of the execution context, the variable object, scope chain, closure, and this pointer will be determined respectively. Generally speaking, there are multiple functions in a JavaScript program, and the JavaScript engine uses a function call stack to manage the calling order of these functions. The calling sequence of the function call stack is consistent with the stack data structure.


2. Understand breakpoint debugging tools

In Try to use the latest version of Chrome browser (I'm not sure the old version you are using is the same as mine), bring up the developer tools of Chrome browser.

Three vertical dots in the upper right corner of the browser -> More Tools -> Developer Tools -> Sources


The interface is as shown.

Advanced front-end basics (6): Observe function call stacks, scope chains and closures in Chrome developer tools

In my demo, I put the code in app.js and introduce it in index.html. For now, we only need to focus on the red arrow in the screenshot. Above the far left, there is a row of icons. We can control the execution order of functions by using them. From left to right, they are:

● resume/pause script execution

Resume/pause script execution

● step over next function call

, the actual performance is not encountered When the function is reached, perform the next step. When a function is encountered, the next step is executed directly without entering the function.

● step into next function call

Step into, the actual performance is that when the function is not encountered, the next step is executed. When a function is encountered, the function execution context is entered.

● step out of current function

Step out of the current function

● deactivate breakpoints

Deactivate breakpoints

● don't pause on exceptions

Non-pause exception capture

Among them, crossing over, stepping into, and jumping out are the three operations I use most.

The second red arrow on the left side of the above picture points to the function call stack (call Stack). The changes in the call stack during code execution are displayed here.

The third red arrow on the left points to the scope chain (Scope), where the scope chain of the current function will be displayed. Where Local represents the current local variable object, and Closure represents the closure in the current scope chain. With the help of the scope chain display here, we can intuitively determine who is the closure in an example, which is very helpful for an in-depth understanding of closures.


3. Breakpoint settings

In the display code Click on the line number to set a breakpoint. Breakpoint settings have the following characteristics:

Breakpoints cannot be set on the line where a separate variable is declared (if no value is assigned) or a function is declared.

After setting a breakpoint and refreshing the page, the JavaScript code will be executed to the breakpoint location and paused. Then we can start debugging using the operations introduced above.

When you set multiple breakpoints, the chrome tool will automatically determine to start execution from the earliest breakpoint, so I usually just set one breakpoint.


##4. Example
Next, we use For some examples, let’s use the breakpoint debugging tool to see how our demo function performs during execution.

// demo01

var fn;
function foo() {
    var a = 2;
    function baz() { 
        console.log( a );
    }
    fn = baz; 
}
function bar() {
    fn(); 
}

foo();
bar(); // 2

Before reading further, we can stop and think about it, who is the closure in this example?

这是来自《你不知道的js》中的一个例子。由于在使用断点调试过程中,发现chrome浏览器理解的闭包与该例子中所理解的闭包不太一致,因此专门挑出来,供大家参考。我个人更加倾向于chrome中的理解。

● 第一步:设置断点,然后刷新页面。

Advanced front-end basics (6): Observe function call stacks, scope chains and closures in Chrome developer tools


● 第二步:点击上图红色箭头指向的按钮(step into),该按钮的作用会根据代码执行顺序,一步一步向下执行。在点击的过程中,我们要注意观察下方call stack 与 scope的变化,以及函数执行位置的变化。

一步一步执行,当函数执行到上例子中

Advanced front-end basics (6): Observe function call stacks, scope chains and closures in Chrome developer tools

我们可以看到,在chrome工具的理解中,由于在foo内部声明的baz函数在调用时访问了它的变量a,因此foo成为了闭包。这好像和我们学习到的知识不太一样。我们来看看在《你不知道的js》这本书中的例子中的理解。

Advanced front-end basics (6): Observe function call stacks, scope chains and closures in Chrome developer tools

书中的注释可以明显的看出,作者认为fn为闭包。即baz,这和chrome工具中明显是不一样的。

而在备受大家推崇的《JavaScript高级编程》一书中,是这样定义闭包。

Advanced front-end basics (6): Observe function call stacks, scope chains and closures in Chrome developer tools

Advanced front-end basics (6): Observe function call stacks, scope chains and closures in Chrome developer tools

这里chrome中理解的闭包,与我所阅读的这几本书中的理解的闭包不一样。具体这里我先不下结论,但是我心中更加偏向于相信chrome浏览器。

我们修改一下demo01中的例子,来看看一个非常有意思的变化。

// demo02
var fn;
var m = 20;
function foo() {
    var a = 2;
    function baz(a) { 
        console.log(a);
    }
    fn = baz; 
}
function bar() {
    fn(m); 
}

foo();
bar(); // 20

这个例子在demo01的基础上,我在baz函数中传入一个参数,并打印出来。在调用时,我将全局的变量m传入。输出结果变为20。在使用断点调试看看作用域链。

Advanced front-end basics (6): Observe function call stacks, scope chains and closures in Chrome developer tools

是不是结果有点意外,闭包没了,作用域链中没有包含foo了。我靠,跟我们理解的好像又有点不一样。所以通过这个对比,我们可以确定闭包的形成需要两个条件。

● 在函数内部创建新的函数;

● 新的函数在执行时,访问了函数的变量对象;

还有更有意思的。

我们继续来看看一个例子。

// demo03

function foo() {
    var a = 2;

    return function bar() {
        var b = 9;

        return function fn() {
            console.log(a);
        }
    }
}

var bar = foo();
var fn = bar();
fn();

在这个例子中,fn只访问了foo中的a变量,因此它的闭包只有foo。

Advanced front-end basics (6): Observe function call stacks, scope chains and closures in Chrome developer tools

修改一下demo03,我们在fn中也访问bar中b变量试试看。

// demo04

function foo() {
    var a = 2;

    return function bar() {
        var b = 9;

        return function fn() {
            console.log(a, b);
        }
    }
}

var bar = foo();
var fn = bar();
fn();

Advanced front-end basics (6): Observe function call stacks, scope chains and closures in Chrome developer tools

这个时候,闭包变成了两个。分别是bar,foo。

我们知道,闭包在模块中的应用非常重要。因此,我们来一个模块的例子,也用断点工具来观察一下。

// demo05
(function() {

    var a = 10;
    var b = 20;

    var test = {
        m: 20,
        add: function(x) {
            return a + x;
        },
        sum: function() {
            return a + b + this.m;
        },
        mark: function(k, j) {
            return k + j;
        }
    }

    window.test = test;

})();

test.add(100);
test.sum();
test.mark();

var _mark = test.mark();
_mark();

Advanced front-end basics (6): Observe function call stacks, scope chains and closures in Chrome developer tools

1Advanced front-end basics (6): Observe function call stacks, scope chains and closures in Chrome developer tools

1Advanced front-end basics (6): Observe function call stacks, scope chains and closures in Chrome developer tools


1Advanced front-end basics (6): Observe function call stacks, scope chains and closures in Chrome developer tools

注意:这里的this指向显示为Object或者Window,大写开头,他们表示的是实例的构造函数,实际上this是指向的具体实例

上面的所有调用,最少都访问了自执行函数中的test变量,因此都能形成闭包。即使mark方法没有访问私有变量a,b。

我们还可以结合点断调试的方式,来理解那些困扰我们很久的this指向。随时观察this的指向,在实际开发调试中非常有用。

// demo06

var a = 10;
var obj = {
    a: 20
}

function fn () {
    console.log(this.a);
}

fn.call(obj); // 20

1Advanced front-end basics (6): Observe function call stacks, scope chains and closures in Chrome developer tools

更多的例子,大家可以自行尝试,总之,学会了使用断点调试之后,我们就能够很轻松的了解一段代码的执行过程了。这对快速定位错误,快速了解他人的代码都有非常巨大的帮助。大家一定要动手实践,把它给学会。

Finally, based on the above exploration situation, let’s summarize the closure again:

The closure is only confirmed to be created when the function is called and executed.

The formation of closures is directly related to the access sequence of the scope chain.

A closure will be formed only when the internal function accesses the variable object in the upper scope chain. Therefore, we can use closures to access variables inside the function.

The closure understood in chrome is very different from the closure understood in "JS You Don't Know" and "JavaScript Advanced Programming". I personally tend to believe in chrome. I won’t jump to conclusions here. You can confirm it yourself after exploring based on my ideas. In a previous article, I made a definition based on what I learned from the book. I think it was wrong. It has been revised now. I'm sorry to everyone.

Statement
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
JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

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

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.