Const {a,obj} = require(‘requireVariable’); const {a,obj} = require(‘requireVariable’); Let a = 1,obj = {a:1}; If you change the property in obj in requireVariable, the reference address will not change. If you reassign a new object in requireVariable, the reference address will change to a new one, but the reference address will still refer to the original reference address, so there is no impact on the reference

/*requireVariable*/
let a = 1;
exports.a=a;
let obj={a:1};
exports.obj=obj;
exports.changeObj = function () {   obj.a=2  }; / / useful
exports.rewriteObj = function(){obj={}} It's no use / /
exports.changeA = function () {  a=2} It's no use / /

Copy the code
const {changeA,changeObj,a,obj,rewriteObj} = require('./require')
console.log('a',a) //a 1
console.log('obj={a:1}',obj); //obj={a:1} { a: 1 }
changeA() //change a 1
console.log('change a',a)
changeObj()
console.log('changeObj obj.a=2',obj)
rewriteObj()
console.log("rewriteObj obj={}", obj);

Copy the code

However,import reference is equivalent to establishing a mapping relationship. Whether it is to rewrite objects or variables, the imported variable and the imported variable point to the same address. Therefore, when changing the value of the imported variable, the variable of the reference side will be modified

// importvariable.js // referenced
export let b = {b:1}
export let c = 1
export function changeB(){
    b.b=2;
}
export function rewriteB() { 
    b = {b:3}}export function rewriteC(){
    c=2
}
Copy the code

/ / reference

import {b,changeB,rewriteB,c,rewriteC} from './import.js';
console.log(b)//{b:1}
changeB()
console.log(b)//{b:2}
rewriteB()
console.log(b)//{b:3}
console.log('c',c) // c 1
rewriteC()
console.log('c',c) // c 2
Copy the code

References are equivalent to putting the code in a file. Changes in the same scope will change at the same time

let b = {b:1}
let c = 1
function changeB(){
    b.b=2;
}
function rewriteB() { 
    b = {b:3}}function rewriteC(){
    c=2
}
console.log(b)//{b:1}
changeB()
console.log(b)//{b:2}
rewriteB()
console.log(b)//{b:3}
console.log('c',c) // c 1
rewriteC()
console.log('c',c) // c 2
Copy the code