当前位置:网站首页>[practice leads to truth] is the introduction of import and require really the same as what is said on the Internet

[practice leads to truth] is the introduction of import and require really the same as what is said on the Internet

2022-07-07 04:43:00 Concise200

import and require

I did a problem when I did the pen test today , As shown in the figure
 Insert picture description here
The correct answer is as follows :

 Insert picture description here
According to the online statement, it is correct , because require Import is similar to shallow copy ( If there is a shallow copy of the North nose , You can see Yiwen teaches you to distinguish assignment 、 Shallow copy and deep copy

But the Internet also says

require adopt module.exports The exported value can no longer change ,import adopt export The exported value can be changed ;

Is it true ???

A wave of shallow practice

// a.js
let a = 1
let b = {
    }
setTimeout(() => {
        
a = 2    
b.b = 2
}, 100)

export default{
    
    a,
    b
}
import a from './a.js'
console.log(a.a)
console.log(a.b)
setTimeout(() => {
        
console.log(a.a)    
console.log(a.b)
}, 500)

According to the online results , The answer should be

1
{}
2
{ b: 2 }

But in fact
 Insert picture description here
In the above performance , Both are similar Shallow copy The operation of , It is not the same as what is said on the Internet a Will become 2.

However, if on-demand import is adopted , The basic data type and reference data type change together

let a = 1
let b = {
    }
setTimeout(() => {
        
a = 2    
b.b = 2
}, 100)

export{
    
    a,
    b
}

//  Or write like this 
/*export let a = 1 export let b = {} setTimeout(() => { a = 2 b.b = 2 }, 100)*/
import {
    a,b} from './a.js'
console.log(a)
console.log(b)
setTimeout(() => {
        
console.log(a)    
console.log(b)
}, 500)

The result is shown in the figure
 Insert picture description here
summary :

  • The default is derived and require It's all shallow copies
  • On demand export is quote , Whether basic data type or reference type , as long as Exporter Change , Import side Will change .
原网站

版权声明
本文为[Concise200]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/188/202207062151433030.html

随机推荐