Question 26: Introduce the development history of modularization
It can be considered from IIFE, AMD, CMD, CommonJS, UMD, webpack(require.ensure), ES Module,
【 To be understood 】
27. In the global scope, variables declared with const and let are not on the window, so where are they? How to get it?
Don’t understand?
Const and let generate block-level scopes, which can be understood as
let a = 10;
const b = 20;
// Equivalent to:
(function(){
var a = 10;
var b = 20; }) ()Copy the code
ES5 has no concept of block-level scope, only functional scope, which can be understood approximately like this. Therefore, the outer window must be inaccessible.
GlobalEnv is a composite environment consisting of a global object environment (objEnv) and a general declaration environment (declsEnv). It is a dual environment. Unified delivery of an environment access interface (objEnv/declsEnv corresponds to Global/Script). The let/const declaration is in declsEnv, whereas the var variable is declared in ObjEnv, so the let/const declaration is not in the window. 【 To be understood 】
Question 33: What does the following code print and why?
var b = 10;
(function b(){
b = 20;
console.log(b); }) ();Copy the code
Print:
ƒ b(){
b = 20;
console.log(b);
}
Copy the code
Because in non-anonymous self-executing functions, function variables are read-only and cannot be modified. Uncaught TypeError: Assignment to constant variable TypeError: Assignment to constant variable There are Windows.
var b = 10;
(function b() {
window.b = 20;
console.log(b); // [Function b]
console.log(window.b); // 20 is inevitable}) ();Copy the code
Var:
var b = 10;
(function b() {
var b = 20; // IIFE internal variables
console.log(b); Function b is created by window.
console.log(window.b); / / 10}) ();Copy the code
Problem 34: Simply modify the following code to print 10 and 20, respectively.
var b = 10;
(function b(){
b = 20;
console.log(b); }) ();Copy the code
Modification:
var b = 10;
(function b(){
var b = 20;
console.log(window.b);
console.log(b); }) ();Copy the code
Or replace window.b with this.b.
Question 41: What does the following code output
var a = 10;
(function () {
console.log(a)
a = 5
console.log(window.a)
var a = 20;
console.log(a)
})()
Copy the code
10, 5, 20 (wrong). Undefined 10 20 (correct).
Because in the immediate function, var a = 20; The local variable a is promoted to the top of the body of the immediately executed function due to js’s variable declaration promotion mechanism. Since such promotion does not include assignment, the first print statement will print undefined, and the last print statement will print 20.
A = 5 due to variable declaration promotion; This statement is executed when the local variable a has already been declared, so the effect is to assign a value to the local variable A, while window.a is still the original 10. Is it because variables with var are promoted first? Is variable promotion performed first in the engine?