1. The data exported from es6 module is a mapping of values, and it is read-only. If the exported variable is changed, an error will be reported
let name= 'I'm a'
function changeName(){
name='A's name has changed.'
}
function getName(){
return name
}
export {name,changeName,getName}
Copy the code
b.js
import {name,changeName,getName} from 'a.js console.log(name) // I am a name='Antenna baby'// VM4797 WAService. Js :2 Error: "name" is read-only. ChangeName () console.log(name) // A's name has changed console.log(getName()) // A's name has changedCopy the code
2.comMonjs exported value is a copy of the value can be changed, and the change of the value in the module will not affect the change of the exported value
let name= 'I'm a'
function changeName(){
name='A's name has changed.'
}
function getName(){
return name
}
exports.name = name
exports.changeName = changeName
exports.getName = getName
Copy the code
B. Changes in the js module do not affect changes in exported values
let a = require('a')
console.log(name) / / I am a
changeName()
console.log(name) / / I am a
console.log(getName()) // The name of a has changed
Copy the code
The value of an object is copied from its location in memory, so it is actually the same object in the module
Here are some examples
(1) Es6 Module
a.js
let xiaoming= {name:'Ming'.age:'ten years'}
function changeName(){
xiaoming.name='Ming'
}
function getName(){
return xiaoming
}
export {name,changeName,getName}
Copy the code
b.js
import {xiaoming,changeName,getName} from 'a.js console.log(xiaoming. Name) // xiaoming='Antenna baby'// VM4797 WAService. Js :2 Error: "name" is read-only. // If you want to change the value of xiaoming, you will not get an error.I change name!'console.log(xiaoming. Name) // Change the value in the module changeName() console.log(xiaoming Console. log(xiaoming===getName()) //true // The same object is in the console xiaoming.name='I change name!'console.log(xiaoming. Name) // I changed my name console.log(getName().name) // I changed my nameCopy the code
(2) CommonJS
a.js
let xiaoming= {name:'Ming'.age:'ten years'}
function changeName(){
xiaoming.name='Ming'
}
function getName(){
return xiaoming
}
exports.xiaoming = xiaoming
exports.changeName = changeName
exports.getName = getName
Copy the code
b.js
let a = require('a')
console.log(a.xiaoming.name) / / xiao Ming
// Change the value in the module
changeName()
console.log(a.xiaoming.name) / / daming
console.log(getName().name) / / daming
// Both the module and the exported object are the same object
console.log(xiaoming===getName()) //true
// Also changes the value inside the external change
a.xiaoming.name='I changed my name.'
console.log(a.xiaoming.name) // I changed my name
console.log(getName().name) // I changed my name
Copy the code
Conclusion the above