Reputation: 373
Hypothetically I have two JS files that are imported using webpack. I want to create global variables which I can use throughout my app. The problem is that I'm unable to do so after a lot of trial by error. I've seen a similar question asked but this scenario is unique (plus the answers didn't work)
I've scaled this down to it's most simple form that should explain what I'm attempting to do.
one.js
class oneJS {
constructor() {
var windowWidth = $(window).width()
}
}
export default oneJS
two.js
class twoJS {
constructor() {
if (windowWidth >= 1200) {
console.log('greater than');
} else {
console.log('less than');
};
}
}
export default twoJS
index.js
import oneJS from 'one.js';
new oneJS();
import twoJS from 'two.js';
new twoJS();
As always, thanks in advance.
Upvotes: 0
Views: 1117
Reputation: 7396
You could store your value as an instance property on OneJS and utilize constructor injection to inject the oneJs instance to all your other class instances that need to access the same value, e.g.
one.js
class OneJS {
constructor() {
this.windowWidth = $(window).width(); // Store the value on the instance
}
}
export default OneJS;
two.js
class TwoJS {
constructor(one) {
if (one.windowWidth >= 1200) {
console.log('greater than');
} else {
console.log('less than');
}
}
}
export default TwoJS
index.js
import OneJS from 'one.js';
import TwoJS from 'two.js';
const oneJS = new OneJS();
new TwoJS(oneJS);
Upvotes: 2