2

I have an entry point class called app.js. This loads various classes. In one of these classes I delcare a constant:

class Product{

    constructor(){
        const height = 100;
        ....

How can I access this variable from other classes without having to import the product class into each class that I wish to access it in?

Alternatively if this is not possible with a const how can it be done? How can I declare a var in a child class of app.js and access it in another child class of app.js without importing the class in which the vairable was declared?

panthro
  • 22,779
  • 66
  • 183
  • 324
  • Are you sure that you [really want a local variable in your class](http://stackoverflow.com/q/13418669/1048572) at all? – Bergi Oct 23 '15 at 10:18

1 Answers1

3

You could export the const as well as the class, but you'd need to do this at the module level rather than inside the class constructor.

product.js

export const height = 100;
export class Product {
   ...
}

app.js

import {height} from "./Product";
console.log(height); // 100

If you still want height to be a part of the Product class, I'm afraid there's no way to access it without somehow importing Product first.

CodingIntrigue
  • 75,930
  • 30
  • 170
  • 176
  • Interesting, would this work if height changed during execution? Would the new height be imported. I know it's a const but I could make it a const object. – panthro Oct 23 '15 at 09:52
  • Good question. I *think* it should be a reference to the same object so that should work (assuming you changed it from a primitive, as you say). But that might depend on the module loader implementation – CodingIntrigue Oct 23 '15 at 09:55
  • 1
    @panthro: A `const` doesn't change its value. Yes, if you make it an object, the reference value will be imported, and mutations to the properties are visible. – Bergi Oct 23 '15 at 10:19
  • 1
    @panthro: import/exports are special. If you change it to `let` and assign a new value later, then yes, the value updates where it is imported. However, since ES6 modules are not natively supported anywhere, it depends on the transpiler and module loader whether this works. Babel supports it for example. – Felix Kling Oct 23 '15 at 14:19