1

I guess it is quite regular issue, but for some reason I cannot find the answer on the net.

So I have a class A:

class A {
   const data = {...}
} 

And a class B in a separate js file.

class B {
   // how can I get const data here?
}  
6
  • 2
    Even if someone answers you, I don't think this is your real code for which you cannot guarantee the answer will work. So the code does not make sense which you have provided. Commented Nov 22, 2018 at 9:14
  • @AnkitAgarwal - don't complicate things by trying to judge code snippets on the merit of how 'real' they are. Just take it as a hypothetical, doesn't need to be a real-world scenario as long as it is specific enough. Not specific? Then request clarity. Commented Nov 22, 2018 at 9:15
  • @Barth - in which context? Web? If so, depending on what it is you want to share, a variable on the page will be globally accessible to all. Whether this makes sense design-wise depends on the requirements. Commented Nov 22, 2018 at 9:15
  • @JᴀʏMᴇᴇ then why are you asking the above question to OP if you think I am complicating the things. Commented Nov 22, 2018 at 9:17
  • @AnkitAgarwal - what are you talking about? We were both making 2 entirely different points!? I'm asking for clarification. Commented Nov 22, 2018 at 9:25

2 Answers 2

3

You could use composition, and instantiate new instance of class A inside of constructor of class B.

class A {
  constructor() {
    this.data = { foo: "bar" };
  }
}

class B {    
  constructor() {
    this.instanceOfA = new A();
    console.log(this.instanceOfA.data);
  }
}

console.log(new B());
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for your answer. What if in class A my variable is located in the body(I mean not in the constructor)?
I don't think that's valid syntax of ES6. Or do you use some other version?
1

Here is data passed by function/event in two class:

   class A {
     constructor(name) {
       console.log(name)
     }
    }

    class B {    
      y(){
        return "ram"
      }
    }

    let resultFromB = (new B().y());
    new A(resultFromB)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.