Home > Web Front-end > JS Tutorial > body text

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

青灯夜游
Release: 2023-04-18 17:16:51
forward
1086 people have browsed it

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.

// 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:

// 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
/* 模拟私有方法 */
// 模拟对象的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
/* setTimeout中使用 */
// setTimeout(fn, number): fn 是不能带参数的。使用闭包绑定一个上下文可以在闭包中获取这个上下文的数据。
function func(param){ return function(){ alert(param) }}
const f1 = func(1);setTimeout(f1,1000);
Copy after login
/* 生产者/消费者模型 */
// 不使用闭包
// 生产者
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
/* 实现继承 */
// 以下两种方式都可以实现继承,但是闭包方式每次构造器都会被调用且重新赋值一次所以,所以实现继承原型优于闭包
// 闭包
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

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

相同的配方再来一刀

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!

Related labels:
source:juejin.cn
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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!