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. and
import
It has lifting effect. - The variable is loaded in the problem
count
, reassigning it will return an error becausecount
It’s just a read-only interface
knowledge
import
The variables in the command input are read-onlyimport
The command is promoted to the head of the entire module and is executed firstimport
It is statically executed and cannot use expressions and variablesimport
isThe Singleton pattern
1. The import command
The input variable is read-only
import
Is 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 command
Has the effect of promotion, will be promoted to the head of the entire module, execute first
The import command
It is executed at compile time, before the code executes
3. import
It 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. import
isSingleton
model
- Repeat the same sentence many times
The import statement
Is 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.