1

The question might sound a bit confusing so I'll let the code explain:

function Foo(arg) {
  const argument = arg;
  const fooPart = new FooPart(this);

  this.printArg = function() {
    console.log(argument);
  }
}

function FooPart(foo) {
  this.parent = foo;

  this.parent.printArg();

}
let foo = new Foo("this is the argument");

This is not working for me. How can I solve this problem or better - what would be the correct approach for this?

Thanks

4
  • 4
    It is this.parent.printArg() ... And you call printArg() before it is defined ... Commented Aug 14, 2019 at 13:57
  • 1
    You have not assigned a function to this.printArg by the time you're trying to call it. Commented Aug 14, 2019 at 13:59
  • yeah it is like this in the original problem sorry I fixed it. @deceze yeah works when I create FooPart after defining printArg thanks! I'm used to Java so that feels strange because the class gets very untidy. is there an other way to do this? Commented Aug 14, 2019 at 14:00
  • 2
    @BlakkM9 It was already mentioned but just to clarify: On line 3, you call FooPart (which calls printArg). On line 5, you define printArg. You are calling printArg before defining it. Commented Aug 14, 2019 at 14:01

2 Answers 2

3

function Foo(arg) {
    this.argument = arg;
    this.fooPart = new FooPart(this);
}

Foo.prototype.printArg = function() {
    console.log(this.argument);
}

function FooPart(foo) {
    this.parent = foo;
    this.parent.printArg();
}

let foo = new Foo("this is the argument");

  1. You should call FooPart after printArg definition
  2. You should use this.parent to access parent
Sign up to request clarification or add additional context in comments.

3 Comments

I guess there is no way to make this more tidy, right?
We can make it more tidy, yes. I will have updated one soon.
You should take a look for prototype and Class or defineProperty
2

The problem is that you define printArg after trying to call it.

The traditional way to define a "class" which doesn't have this problem would be:

function Foo(arg) {
  this.argument = arg;
  this.fooPart = new FooPart(this);
}

Foo.prototype.printArg = function() {
  console.log(this.argument);
}

function FooPart(foo) {
  this.parent = foo;
  this.parent.printArg();
}

let foo = new Foo("this is the argument");

The more modern version to define an "actual" class is:

class Foo {
  constructor(arg) {
    this.argument = arg;
    this.fooPart = new FooPart(this);
  }

  printArg() {
    console.log(this.argument);
  }
}

class FooPart {
  constructor(foo) {
    this.parent = foo;
    this.parent.printArg();
  }
}

let foo = new Foo("this is the argument");

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.