我有一个 javascript 文件(我们称之为 newconfig.js),它通过 config.js 文件中的 require() 操作包含一个模块(对象类型):
考虑 core.js 是:
module.exports = {
configuration: {
showLanguageSelector: false
},
tableStructure: {
columns: [
{
tooltip: 'Indicates if this load has alerts or notes',
name: 'Alerts <em>& Notes</em>'
},
{
tooltip: 'Trailer number and trailer type',
name: 'Trailer <em>Type</em>'
},
{
tooltip: 'Door number',
name: 'Door'
},
{
tooltip: 'Trailer opened date/time',
name: 'Open<span>ed</span>'
},
{
tooltip: 'Trailer closed date/time',
name: 'Closed'
}
]
}
};
我的 newconfig.js 文件包含:
const core = require('./core/config');
然后我在我的文件中克隆核心实例:
let config = Object.assign({}, core);
然后我改变我的本地对象
config.Configuration = {
showLanguageSelector: true
};
config.tableStructure.columns = [
{
tooltip: 'Indicates if this load has alerts or notes',
name: 'Alerts <em>& Notes</em>',
}, {
tooltip: 'Trailer number and trailer type',
name: 'Trailer <em>Type</em>',
}
];
这样我就可以将其导出为扩展核心配置的另一个配置:
module.exports = config;
当外部文件尝试在本地包含 ./core/config 文件以使用时,它具有 newconfig.js 的更改
IE(mylayout.js):
const core = require('./core/config');
console.log(core);
输出时的核心价值是:
{
Configuration: {
showLanguageSelector: false // interesting how this wasn't mutated!!!!!
},
tableStructure {
columns: [
{
tooltip: 'Indicates if this load has alerts or notes',
name: 'Alerts <em>& Notes</em>',
}, {
tooltip: 'Trailer number and trailer type',
name: 'Trailer <em>Type</em>',
}
]
}
}
如果我在更改对象之前将对象克隆到新对象并导出该新对象,我会在哪里出错导致我的原始核心配置发生突变?
在另一个 js 文件中要求我的 newconfig.js 会返回所需的行为:
{
Configuration: {
showLanguageSelector: true
},
tableStructure {
columns: [
{
tooltip: 'Indicates if this load has alerts or notes',
name: 'Alerts <em>& Notes</em>',
}, {
tooltip: 'Trailer number and trailer type',
name: 'Trailer <em>Type</em>',
}
]
}
}