0

Consider the below:

class foo(){
   constructor(){this.x = 10}
   f(){console.log(this.x)}
}
myfoo = new foo()
class bar{
    constructor()
    b(func){func()}
}
mybar = new bar()
mybar.b(myfoo.f())

Because of how this works in JavaScript, "this" in myfoo.f points to mybar instead of myfoo. How do I go around this? Also, why does JavaScript do this?

Response to duplicate

Before reporting this as a duplicate again, please note that this question is directed to the JavaScript class, not functions in this link. I don't think that link does not resolve my issue.

halfer
  • 19,824
  • 17
  • 99
  • 186
smaillis
  • 298
  • 3
  • 12
  • 2
    "*please note that this question is directed to the javacript class, not functions*" - `class` methods *are* functions. Please read and understand the answers to the linked duplicate in detail, they *do* solve your problem. – Bergi Nov 06 '21 at 05:36
  • 1
    If your question is already closed, please do not repost it. What you can do: firstly, try to resolve the issue in the comments of the original question. If that does not yield a result you are happy with, post a question about the dup closure to [Meta Stack Overflow](https://meta.stackoverflow.com/). You can get a second opinion there. Do note however that gold badge holders (who can close a question as a dup on their own) are experts in their field, so their assessments of what is a duplicate are usually likely to be correct. – halfer Nov 07 '21 at 22:50

0 Answers0