3

The code structre is quite simple:

class A {
    b = 1
    c = {
        d () {
            console.log(this.b) //=> undefined
            //how can i access b here?
        }
    }
}

I would prefer a not so hacky workaround since this is a core piece of code for the project i am working on

2
  • What is d? It looks like you mean for d to be a function. In which case, you should write function d() {} (or d: function() {} within your c object) rather than d() {}. Arrow notation is a compact and more limited version of function. Commented Dec 21, 2021 at 0:24
  • @Euthyphro shorthand function notations in objects have been a feature in js since ES2015 Commented Dec 21, 2021 at 0:47

1 Answer 1

5

You could use an arrow function to preserve this where the function is being declared:

class A {
    b = 1
    c = {
        d: () => console.log(this.b)
    }
}

const a = new A;
a.c.d();

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

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.