0

I have a class B which implements another class A.

In the class A I need to use variables defined in class B

class  classA {
    methodA() {
        console.log(parentClass.variableToRetrieve);
    }
}


class classB {
    constructor() {
        this.variableToRetrieve = 1;
        this.A = new classA();
    }
}

var B = new classB();
B.A.methodA();

Whats should I use in classA.methodA ans see 1 in the console ?

Edit

I already thougth to pass the B object in the classA constructor, or pass values, but as I can have hundreds variables and (potentially) millions classA, it will overload the server quickly

3
  • classB doesn't implement classA it just has a variable that is an instance of classA. Commented Mar 11, 2018 at 8:12
  • this.A = new classA(this.variableToRetrieve); Commented Mar 11, 2018 at 8:16
  • As I have a lot of variables, it's not a good idea. I have a hundred parameters and I can have millions of class A :( Commented Mar 11, 2018 at 8:44

2 Answers 2

1

You should extend classB with classA

class  classA {

    methodA() {
        console.log('parentClass.variableToRetrieve');
    }

}

class classB extends classA {
    constructor() {
        super()
        this.variableToRetrieve = 1;
    }

    method() {
        this.A = new classA();
    }

}
var B = new classB();
B.methodA();

Updated: I think binding the classB will solve will problem.

class  classA {
    methodA() {
        console.log(this.variableToRetrieve);
    }
}


class classB {
    constructor() {
        this.variableToRetrieve = 4;
    }
}

var B = new classB();
var A = new classA();
A.methodA.bind(B)();

Sign up to request clarification or add additional context in comments.

4 Comments

The problem is I can't extend the class, because the main class is a container for class B objects. which can be images, particles, primitives, geopositions,... And in the class B I have some informations like positions, colors, ...
Sorry did not understand the point why you can't extend the classA. I think classB and classA are related. where classA is the base class and classB will extend classA and add few more information.
Imagine class B is the world and class A is a car. A car can't herits from the word but in my car object I need to know some world's values
Yes the class binding seems to be the best solution
0

Your class A must extend class class B to do that

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.