【发布时间】:2019-05-29 21:56:01
【问题描述】:
//lib-es6.js
export let counter = 3;
export function incCounter() {
counter++;
}
来自16.7.2 section,即使我们通过星号 (*) 导入模块,导入的值也不能更改。
//main-es6.js
import * as lib from './lib-es6'; // imported via asterisk(*)
// The imported value `counter` is live
console.log(lib.counter); // 3 . => I expected this
lib.incCounter();
console.log(lib.counter); // 4 . => I expected this
/****************************************/
// But I was able to change lib.counter.
// Question: Can we change imported value in ES6 if we import it via asterisk (*)?
lib.counter++; // Not an error. ==> I DID NOT expected this.
console.log(lib.counter); // 5
/****************************************/
【问题讨论】:
-
我的猜测:
lib指的是具有counter属性的对象,并且该属性不是不可变的。 -
你是直接在 node 中运行代码(在那种情况下是哪个版本)还是先通过 babel 之类的东西编译它?
-
@Markus-ipse 是的,我使用的是 babel7,node10。我正在使用 "@babel/core": "^7.4.5", "@babel/node": "^7.4.5"
-
看起来你的转译器没有发现这个错误。这可能取决于 babel 选项,但
.counter应该是没有 setter 的 getter。
标签: ecmascript-6 es6-modules es6-module-loader