【问题标题】:ES6 - How to modify a variable in other modulesES6 - 如何修改其他模块中的变量
【发布时间】:2017-12-04 14:07:55
【问题描述】:

在模块 Global.js 中:

export let transLog = [];

主要:

import * as G from "./Global";
G.transLog = [];

我遇到了一个错误:

app.js?c99e:19 Uncaught TypeError: Cannot set property q of #<Object> which has only a getter
    at eval (app.js?c99e:19)
    at Object.<anonymous> (bootstrap e92860b74eb6dd40b159:62)
    at __webpack_require__ (bootstrap e92860b74eb6dd40b159:19)
    at bootstrap e92860b74eb6dd40b159:62
    at bootstrap e92860b74eb6dd40b159:62

webpack 配置:

const webpack = require('webpack');

module.exports = {
    entry: './js/app.js',
    plugins: [
        new webpack.SourceMapDevToolPlugin({
            filename: "[file].map"
        })
    ],
    output: {
        filename: './dist/app.js'
    },
    devtool: 'source-map'
};

那么,如何修改其他模块中的变量呢?

【问题讨论】:

  • 你没有。为什么你需要?你想做什么?
  • 为此目的只导出一个函数:在第一个模块中:let foo = 3; export default function(x) { foo = x; }; 和第二个模块中 import alterFoo from './firstmodule'; alterFoo(4); 所有这些都是简单的 OOP,唯一的区别是我们不必伪造现在我们有了真实的对象和闭包的模块。

标签: javascript ecmascript-6 es6-modules


【解决方案1】:

您不能为导出的变量分配新值,只有模块本身可以这样做(如果这样做,可能会很混乱,所以我建议避免这种情况)。

你可以改变导出的对象,例如G.translog.push(…)G.translog.length = 0

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-16
    相关资源
    最近更新 更多