Write the output of the following code and explain it

// counter.js
let counter = 10;
let add = () = > {
    console.log(counter);
}
export { counter, add };

// index.js
add();
import { counter, add } from './counter.js';
counter += 1;
console.log(counter);
Copy the code

Answer: 10 error

parsing

  • The import module is read-only and cannot be modified. andimportIt has lifting effect.
  • The variable is loaded in the problemcount, reassigning it will return an error becausecountIt’s just a read-only interface

knowledge

  • importThe variables in the command input are read-only
  • importThe command is promoted to the head of the entire module and is executed first
  • importIt is statically executed and cannot use expressions and variables
  • importisThe Singleton pattern

1. The import commandThe input variable is read-only

  • importIs essentially an output interface, that is, it is not allowed to rewrite the interface in the script that loads the module
import { a } from './xxx.js';
a = {}; // Syntax Error: 'a' is read-only
Copy the code
  • A is a read-only interface. But if A is an object, overwriting a’s properties is allowed
// counter.js
let counter = {};
export default counter;

// index.js
import myCounter from './counter.js'; myCounter.hello ='helloCounter';
Copy the code

The myCounter property can be overwritten successfully, and other modules can also read the overwritten value, but this writing method is difficult to check, so it is recommended to treat it as completely read-only.

2. The import commandHas the effect of promotion, will be promoted to the head of the entire module, execute first

  • The import commandIt is executed at compile time, before the code executes

3. importIt is statically executed and cannot use expressions and variables

/ / an error
import { 'f' + 'oo' } from 'my_module';

/ / an error
let module = 'my_module';
import { foo } from module;
Copy the code

4. importisSingletonmodel

  • Repeat the same sentence many timesThe import statementIs executed only once
import { foo } from 'my_module';
import { bar } from 'my_module';

/ / is equivalent to
import{foo, bar}from 'my_module';
Copy the code

Although foo and bar are loaded in two statements, they correspond to the same my_module instance.