a.js
let str="hello";
let update=(s)=>{
str=s;
}
module.exports={
str,
update,
}
b.js
const{str,update}=require("./a");
console.log(str);
update("world");
console.log(str);
有什么方法可以动态修改吗
1
wukongkong 2020 年 12 月 6 日
现在不能吗?好像 important 形式是可以的,一个是传递值,一个是传递引用
|
2
mxT52CRuqR6o5 2020 年 12 月 6 日
module.exports = {
get str(){ return str}, update, } |
3
mxT52CRuqR6o5 2020 年 12 月 6 日
|
4
yazoox 2020 年 12 月 6 日
添加一个方法,getstr(),返回 str 的值。然后,export getstr 方法就可以了。
|
5
morethansean 2020 年 12 月 6 日 用 ES module 或者
exports.str = 123; exports.update = s => exports.str = s; 因为 JS 里通常都是值传递,除了个别情况比如 object(包括数组) 或者 arguments,你赋值给 module.exports 的对象里的 str 属性是一个值不是一个引用。 |
6
SergeGao 2020 年 12 月 6 日
楼上+1, 用 es module 或者用 get
|