Table of Contents
1️⃣ Scope and closure
2️⃣ Prototype and prototype chain
3️⃣ 异步和单线程
Home Web Front-end JS Tutorial Detailed explanation of the three mountains of JS: scope and closure, prototype and prototype chain, asynchrony and single thread

Detailed explanation of the three mountains of JS: scope and closure, prototype and prototype chain, asynchrony and single thread

Apr 18, 2023 pm 05:16 PM
javascript front end

js serves as the backbone of the front-end. So, do you know what the three big mountains of javascript are?

1️⃣ Scope and closure

Scope refers to the current code Context controls the visibility and life cycle of variables and functions. The biggest function is to isolate variables, so variables with the same name in different scopes will not conflict.

Scope chain means that if the value is not found in the current scope, it will query the upper scope until the global scope, such a search process The chain formed is called a scope chain. [Recommended learning: javascript video tutorial]

Scopes can be stacked into a hierarchical structure, and child scopes can access the parent scope, but not vice versa.

Scope can be subdivided into four types: Global scope, Module scope,Function scopeBlock-level scope

##Global scope: The code is in the program Can be accessed anywhere, such as the window object. However, global variables will pollute the global namespace and easily cause naming conflicts.

Module scope: There was no module definition in the early js syntax because the original script was small and simple. Later, as scripts became more and more complex, modular solutions emerged (AMD, CommonJS, UMD, ES6 modules, etc.). Usually a module is a file or a script, and this module has its own independent scope.

Function scope: As the name suggests, the scope created by the function. Closures are generated in this scope, which we will introduce separately later.

Block-level scope: Since js variable promotion has design flaws such as variable coverage and variable pollution, ES6 introduces the block-level scope keyword to solve these problems. Typical cases are the for loop of let and the for loop of var.

1

2

3

4

5

6

7

8

9

10

11

// var demo

for(var i=0; i<10; i++) {

    console.log(i);

}

console.log(i); // 10

 

// let demo

for(let i=0; i<10; i++) {

    console.log(i);

}

console.log(i); //ReferenceError:i is not defined

Copy after login

After understanding the scope, let’s talk about it

Closure: Function A contains function B, and function B uses the variables of function A, then function B A closure or closure is a function that can read the internal variables of function A.

It can be seen that the closure is a product under the function scope. The closure will be created at the same time as the outer function is executed. It is a combination of a function and a reference to its bundled surrounding environment state. In other words,

closure is the non-release of the outer function variable by the inner function .

Characteristics of closure:

    There is a function in the function;
  • Internal functions can access the scope of the outer function;
  • Parameters and variables will not be GCed and always reside in memory;
  • There are closures only where there is memory.
So using closures will consume memory, and improper use will cause memory overflow problems. Before exiting the function, all unused local variables need to be deleted. If it is not for some specific needs, it is unwise to create functions within functions. Closures have a negative impact on script performance in terms of processing speed and memory consumption.

The application scenarios of closures are summarized below:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

// demo1 输出 3 3 3

for(var i = 0; i < 3; i++) {

    setTimeout(function() {

        console.log(i);

    }, 1000);

}

// demo2 输出 0 1 2

for(let i = 0; i < 3; i++) {

    setTimeout(function() {

        console.log(i);

    }, 1000);

}

// demo3 输出 0 1 2

for(let i = 0; i < 3; i++) {

    (function(i){

        setTimeout(function() {

        console.log(i);

        }, 1000);

    })(i)

}

Copy after login

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

/* 模拟私有方法 */

// 模拟对象的get与set方法

var Counter = (function() {

var privateCounter = 0;

function changeBy(val) {

    privateCounter += val;

}

return {

    increment: function() {

    changeBy(1);

    },

    decrement: function() {

    changeBy(-1);

    },

    value: function() {

    return privateCounter;

    }

}

})();

console.log(Counter.value()); /* logs 0 */

Counter.increment();

Counter.increment();

console.log(Counter.value()); /* logs 2 */

Counter.decrement();

console.log(Counter.value()); /* logs 1 */

Copy after login

1

2

3

4

/* setTimeout中使用 */

// setTimeout(fn, number): fn 是不能带参数的。使用闭包绑定一个上下文可以在闭包中获取这个上下文的数据。

function func(param){ return function(){ alert(param) }}

const f1 = func(1);setTimeout(f1,1000);

Copy after login

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

/* 生产者/消费者模型 */

// 不使用闭包

// 生产者

function producer(){

    const data = new(...)

    return data

}

// 消费者

function consumer(data){

    // do consume...

}

const data = producer()

 

// 使用闭包

function process(){

    var data = new (...)

    return function consumer(){

        // do consume data ...

    }

}

const processer = process()

processer()

Copy after login

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

/* 实现继承 */

// 以下两种方式都可以实现继承,但是闭包方式每次构造器都会被调用且重新赋值一次所以,所以实现继承原型优于闭包

// 闭包

function MyObject(name, message) {

  this.name = name.toString();

  this.message = message.toString();

  this.getName = function() {

    return this.name;

  };

 

  this.getMessage = function() {

    return this.message;

  };

}

// 原型

function MyObject(name, message) {

  this.name = name.toString();

  this.message = message.toString();

}

MyObject.prototype.getName = function() {

  return this.name;

};

MyObject.prototype.getMessage = function() {

  return this.message;

};

Copy after login

I seem to understand the concept of closures but seem to be missing something? The meaning is still not finished. I was also lost in closures, but after reading the life cycle of closures, I found myself again.

Detailed explanation of the three mountains of JS: scope and closure, prototype and prototype chain, asynchrony and single thread

After learning, let’s have a quick test

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

function test(a, b){

  console.log(b);

  return {

    test: function(c) {

      return test(c,a);

    }

  }

}

 

var a = test(100);a.test(101);a.test(102);

var b = test(200).test(201).test(202);

var c = test(300).test(301);c.test(302);

 

// undefined  100  100

// undefined  200 201

// undefined  300 301

Copy after login

2️⃣ Prototype and prototype chain

Where there are objects There is

prototype. Each object will initialize a property inside it, which is prototype (prototype), and shared properties and methods are stored in the prototype. When we access the properties of an object, the js engine will first check whether the current object has this property. If not, it will check whether its prototype object has this property, and so on until the Object built-in object is retrieved. Such a search process formed the concept of prototype chain.

The most important thing to understand the prototype is to clarify the relationship between __proto__, prototype, and constructor. Let’s take a look at a few concepts first:

  • __proto__属性在所有对象中都存在,指向其构造函数的prototype对象;prototype对象只存在(构造)函数中,用于存储共享属性和方法;constructor属性只存在于(构造)函数的prototype中,指向(构造)函数本身。
  • 一个对象或者构造函数中的隐式原型__proto__的属性值指向其构造函数的显式原型 prototype 属性值,关系表示为:instance.__proto__ === instance.constructor.prototype
  • 除了 Object,所有对象或构造函数的 prototype 均继承自 Object.prototype,原型链的顶层指向 null:Object.prototype.__proto__ === null
  • Object.prototype 中也有 constructor:Object.prototype.constructor === Object
  • 构造函数创建的对象(Object、Function、Array、普通对象等)都是 Function 的实例,它们的 __proto__ 均指向 Function.prototype。

看起来是不是有点乱??别慌!!一张图帮你整理它们之间的关系

Detailed explanation of the three mountains of JS: scope and closure, prototype and prototype chain, asynchrony and single thread

相同的配方再来一刀

1

2

3

4

const arr = [1, 2, 3];

arr.__proto__ === Array.prototype; // true

arr.__proto__.__proto__ === Object.prototype; // true

Array.__proto__ === Function.prototype; // true

Copy after login

3️⃣ 异步和单线程

JavaScript 是 单线程 语言,意味着只有单独的一个调用栈,同一时间只能处理一个任务或一段代码。队列、堆、栈、事件循环构成了 js 的并发模型,事件循环 是 JavaScript 的执行机制。

为什么js是一门单线程语言呢?最初设计JS是用来在浏览器验证表单以及操控DOM元素,为了避免同一时间对同一个DOM元素进行操作从而导致不可预知的问题,JavaScript从一诞生就是单线程。

既然是单线程也就意味着不存在异步,只能自上而下执行,如果代码阻塞只能一直等下去,这样导致很差的用户体验,所以事件循环的出现让 js 拥有异步的能力。

Detailed explanation of the three mountains of JS: scope and closure, prototype and prototype chain, asynchrony and single thread

更多编程相关知识,请访问:编程教学!!

The above is the detailed content of Detailed explanation of the three mountains of JS: scope and closure, prototype and prototype chain, asynchrony and single thread. For more information, please follow other related articles on the PHP Chinese website!

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

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

PHP and Vue: a perfect pairing of front-end development tools PHP and Vue: a perfect pairing of front-end development tools Mar 16, 2024 pm 12:09 PM

PHP and Vue: a perfect pairing of front-end development tools. In today's era of rapid development of the Internet, front-end development has become increasingly important. As users have higher and higher requirements for the experience of websites and applications, front-end developers need to use more efficient and flexible tools to create responsive and interactive interfaces. As two important technologies in the field of front-end development, PHP and Vue.js can be regarded as perfect tools when paired together. This article will explore the combination of PHP and Vue, as well as detailed code examples to help readers better understand and apply these two

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

Questions frequently asked by front-end interviewers Questions frequently asked by front-end interviewers Mar 19, 2024 pm 02:24 PM

In front-end development interviews, common questions cover a wide range of topics, including HTML/CSS basics, JavaScript basics, frameworks and libraries, project experience, algorithms and data structures, performance optimization, cross-domain requests, front-end engineering, design patterns, and new technologies and trends. . Interviewer questions are designed to assess the candidate's technical skills, project experience, and understanding of industry trends. Therefore, candidates should be fully prepared in these areas to demonstrate their abilities and expertise.

Is Django front-end or back-end? check it out! Is Django front-end or back-end? check it out! Jan 19, 2024 am 08:37 AM

Django is a web application framework written in Python that emphasizes rapid development and clean methods. Although Django is a web framework, to answer the question whether Django is a front-end or a back-end, you need to have a deep understanding of the concepts of front-end and back-end. The front end refers to the interface that users directly interact with, and the back end refers to server-side programs. They interact with data through the HTTP protocol. When the front-end and back-end are separated, the front-end and back-end programs can be developed independently to implement business logic and interactive effects respectively, and data exchange.

Exploring Go language front-end technology: a new vision for front-end development Exploring Go language front-end technology: a new vision for front-end development Mar 28, 2024 pm 01:06 PM

As a fast and efficient programming language, Go language is widely popular in the field of back-end development. However, few people associate Go language with front-end development. In fact, using Go language for front-end development can not only improve efficiency, but also bring new horizons to developers. This article will explore the possibility of using the Go language for front-end development and provide specific code examples to help readers better understand this area. In traditional front-end development, JavaScript, HTML, and CSS are often used to build user interfaces

Django: A magical framework that can handle both front-end and back-end development! Django: A magical framework that can handle both front-end and back-end development! Jan 19, 2024 am 08:52 AM

Django: A magical framework that can handle both front-end and back-end development! Django is an efficient and scalable web application framework. It is able to support multiple web development models, including MVC and MTV, and can easily develop high-quality web applications. Django not only supports back-end development, but can also quickly build front-end interfaces and achieve flexible view display through template language. Django combines front-end development and back-end development into a seamless integration, so developers don’t have to specialize in learning

See all articles