0

I have a class "Foo" which is compossed by two classes "Bar" and "Baz"

function Foo() {
   this.bar = new Bar();
   this.baz = new Baz();
}

-----------------------------------------

function Bar() {
   this.bar = something1();
}

Bar.prototype.methodN = () => {
   // some stuff with bar
}


-----------------------------------------

function Baz() {
   this.baz = something2();
   this.bar = new Bar();
}

Baz.prototype.method0 = () => {
   // some stuff with baz
}

Baz.prototype.methodN = () => {
   // some stuff with baz and bar
}

Then, if I create an instance of Foo

const foo = new Foo();

how can I call methods of Bar and Baz using foo?

Raul
  • 2,673
  • 1
  • 15
  • 52
  • 2
    `bar` and `baz` are just fields that belong to each instance of `Foo`, so `foo.bar.methodN()`, `foo.baz.method0()`, etc. – kshetline Mar 31 '21 at 03:25

1 Answers1

1

You can simply access all the other classes with dot notation.

function Foo() {
   this.bar = new Bar();
   this.baz = new Baz();
}

function something1() {
  return 'something1'
}

function something2() {
  return 'something2'
}

function Bar() {
   this.bar = something1();
}

Bar.prototype.methodN = () => {
   // some stuff with bar
}



function Baz() {
   this.baz = something2();
   this.bar = new Bar();
}

Baz.prototype.method0 = () => {
   // some stuff with baz
}

Baz.prototype.methodN = () => {
   // some stuff with baz and bar
}

const foo = new Foo()

console.log(foo.bar.bar)
console.log(foo.baz.baz)
console.log(foo.bar.methodN) // can be invoked
Rifat Bin Reza
  • 2,601
  • 2
  • 14
  • 29