0

Okay let's say I have the following:

class Something {
  foo = {
    a: '123',
    get_a() {
      return this.a;
    }
  };

  bar = {
    b: '456',

    get_b() {
      return this.b;
    },

    get_c() {
      return this.get_a();

    }
  };

}
window.s = new Something();
window.s.bar.get_c();

If I were to use s.bar.get_b() it will return '456'. Within get_b() I can reference this.b and it looks to be a reference to bar. However, when I attempt to call s.bar.get_c(), I get an error:

Uncaught TypeError: this.get_a is not a function

Well based on my understanding of this being a reference to bar, I guess that makes sense. However, I don't understand what I need to do to actually reference foo.get_a() from bar.get_c(). I've tried various things but nothing seems to work, short of just using s.foo.get_a() but I don't want to have to directly reference the s object. What am I missing here? I'm starting to suspect I'm fundamentally structuring my class wrong...

Edit: Not sure why someone felt the need to update my post to have it execute the code snippet.. seems overkill ¯_(ツ)_/¯

Anyways.. one thing I should have mentioned: in practice I'm not actually calling s.foo.get_a() from some other context outside of my class functions, which is why I mentioned not wanting to directly reference the s object. I was just putting the full path for sake of clarity!

1 Answer 1

2

Make use of arrow functions:

class Something {
  foo = {
    a: '123',
    get_a() {
      return this.a;
    }
  };

  bar = {
    b: '456',

    get_b() {
      return this.b;
    },

    get_c: () => {
      return this.foo.get_a();
    }
  };

}

const a = new Something();

console.log(a.bar.get_c());

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

2 Comments

I believe this is what I am looking for, yes! Now I just need to research how arrow syntax / functions actually work! Thanks!
@slinkhi Basically, arrow functions doesn't have this. So, when you call it inside it, js will start search for it like normal variables, following parent scope structure. In this case, it will find this in Something class. From there, you can access foo object. Arrow functions helps object oriented designs once it doesn't mess with this variables like normal functions, which has a different this from different scenarios.

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.