Click here to Skip to main content
15,885,097 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Lets say I have two classes.
JavaScript
class childsParent {
    number = 69;
    myChild = new parentsChild;
}

class parentsChild {
    getParentsNumber = function () {
        //console.log childsParent's number
    }
}

myObject = new childsParent;
myObject.myChild.getParentsNumber();


I want the result to print out myObject.number using the parentsChild class.

What I have tried:

I've tried using this.parent, but it doesn't really do anything.
Posted
Updated 8-Dec-22 10:21am

You can't do that since the child has no reference to the parent at all and it's a Bad Idea(TM) to begin with.

Classes should not know anything at all about other classes in the hierarchy that you've come up with. This keeps to the philosophy of "separation of concerns." This makes it possible for you to reuse classes without having them dependent on each other.

TO do inheritance properly, a child class needs to "extend" a parent class. See JavaScript Class Inheritance[^] for more information.
 
Share this answer
 
There is a classic design pattern called "the mediator pattern" that is used in apps and popular game engines that will help you do this.

check this link below for a simple explanation and if you have any questions ask away
Mediator/Middleware Pattern[^]


the parent has an array of children and when a child is created you pass the parent in the constructor. the child will be able to reference the parent and get its number.

class childsParent {
    constructor(){
        this.number = 69;
        this.children = []; 
    }

    getChild(childName){
        const component = this.children.find(child=> child.name === childName);
        if(component){
            console.log(component);
        } else {
            console.log("child not found");
        }
        
    }
}

class parentsChild {
    constructor(name, parent){
        this.name = name;
        this.parent = parent;
        this.parent.children.push(this);
    }

    getParentsNumber(){
        console.log(this.parent.number)
    }
}

const newParent = new childsParent();

const child1 = new parentsChild("child1", newParent);

child1.getParentsNumber(); //69
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900