Home > Article > Web Front-end > Detailed explanation of the three mountains of JS: scope and closure, prototype and prototype chain, asynchrony and single thread
js serves as the backbone of the front-end. So, do you know what the three big mountains of javascript are?
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 scope
、Block-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 definedAfter 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.
closure is the non-release of the outer function variable by the inner function .
Characteristics of closure:
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) }
/* 模拟私有方法 */ // 模拟对象的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 */
/* setTimeout中使用 */ // setTimeout(fn, number): fn 是不能带参数的。使用闭包绑定一个上下文可以在闭包中获取这个上下文的数据。 function func(param){ return function(){ alert(param) }} const f1 = func(1);setTimeout(f1,1000);
/* 生产者/消费者模型 */ // 不使用闭包 // 生产者 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()
/* 实现继承 */ // 以下两种方式都可以实现继承,但是闭包方式每次构造器都会被调用且重新赋值一次所以,所以实现继承原型优于闭包 // 闭包 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; };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. 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
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
.
instance.__proto__ === instance.constructor.prototype
Object.prototype.__proto__ === null
Object.prototype.constructor === Object
看起来是不是有点乱??别慌!!一张图帮你整理它们之间的关系
相同的配方再来一刀
const arr = [1, 2, 3]; arr.__proto__ === Array.prototype; // true arr.__proto__.__proto__ === Object.prototype; // true Array.__proto__ === Function.prototype; // true
JavaScript 是 单线程
语言,意味着只有单独的一个调用栈,同一时间只能处理一个任务或一段代码。队列、堆、栈、事件循环构成了 js 的并发模型,事件循环
是 JavaScript 的执行机制。
为什么js是一门单线程语言呢?最初设计JS是用来在浏览器验证表单以及操控DOM元素,为了避免同一时间对同一个DOM元素进行操作从而导致不可预知的问题,JavaScript从一诞生就是单线程。
既然是单线程也就意味着不存在异步,只能自上而下执行,如果代码阻塞只能一直等下去,这样导致很差的用户体验,所以事件循环的出现让 js 拥有异步的能力。
更多编程相关知识,请访问:编程教学!!
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!