Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
440 views
in Technique[技术] by (71.8m points)

javascript - shared module not seen everywhere where expected

I'm writing the code with a few js classes and modules. I also would like to create one module that will contain all information and methods that are shared between them. So far my code looks like that:

main.js:

let shared = require("./shared");
let rm = module.exports = {};
let main = module.exports = {};
{...}
main.init = () => {
  shared.my_variable = "my_variable"
  main.elem = new rm.Range(); //shared.my_variable is correctly set
  shared.setup()
  {...}
}

rm.js:

let shared = require("./shared");
let rm = module.exports = {};

rm.Range = class {
   constructor() {
      console.log(shared.my_variable);   //shared is just an empty object, shared.my_variable undefined
   }
}

shared.js

let shared = module.exports = {};
shared.my_variable = "";
shared.setup = () => {
  console.log(shared.my_variable);        //shared.my_variable set correctly to "my_variable"
  {...}
}

I am checking the shared in browser console on 3 occasions: in main.js right after setting my_variable and it is fine, in rm.js in the constructor where shared is an empty object and shared.my_variable is undefined and after next line in shared.setup() method where shared.my_variable is again correctly set to "my_variable". Why in Range class I do not have access to shared? How to correctly organise the code so that the shared will be truly shared between the modules and the classes?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...