2

Passing an object of a class using 'this' to another class in Javascript

So, I come from a background of java, c#, python and other languages of that range, and I'm trying to basically recreate something in Javascript.

I want to pass an object of Class A to Class B using 'this' so an instance of Class A can be accessed in Class B.

import B from .....
class A
{
   constructor()
   {
    Obj = new B // Make object of class B

    b(this) // Send instance of class A to class B
   }

 methodA() // Method to test
 {

    alert("Hello!")

 }

}

class B
{

 constructor(a) //receive class A here in class B
 {

    a.methodA // call method of the instance class A

 }

}

I cannot access methodA in b when passing A into B

3
  • You may want to use extends for this: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… Commented Aug 7, 2019 at 20:58
  • No. You have to read up on this and inheritance in javascript. It is not as in Java and IMHO you should not try to shoe horn java-this and java-inheritance into javascript. Instead embrace how Javscript is intended to work. I have no good links for you but the book "Javascript, the good parts" is a good investment in time to read. It tells you where javascript is wrong, quirky and good. Especially the latter is valueable to know, what to embrace. FWIW Commented Aug 7, 2019 at 21:05
  • You can only use this inside a class method, since it's the object that the method was called on. What do you expect b(this) to do outside of a method? Commented Aug 7, 2019 at 21:08

1 Answer 1

2

Since you're using the object in the B constructor, you need to pass this as an argument to new B. There's no b() function anywhere.

You also forgot the parentheses when calling a.methodA().

class A {
  constructor() {
    let Obj = new B(this) // Make object of class B
  }

  methodA() // Method to test
  {
    alert("Hello!")
  }
}

class B {

  constructor(a) //receive class A here in class B
  {
    a.methodA() // call method of the instance class A
  }
}

let a = new A;

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

3 Comments

Hey, thanks for the help. I got it working with your solution, now I want to access method() in another method which isn't in the constructor, say a method below the constructor, when I call a.method() outside the constructor it says 'undefined is not an object' (this.a.methodA()) I understand this is a problem with the scope of the variable, how may I access it outside the constructor? Thank you
You never saved a anywhere. You can do this.a = a; in the constructor, and then use this.a.methodA() elsewhere.
Thank you my friend, best wishes

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.