Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access `this` of a class from an object within the class in javascript

Tags:

javascript

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

like image 309
Mola 1.9 Avatar asked Jan 24 '26 09:01

Mola 1.9


1 Answers

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();
like image 104
Guerric P Avatar answered Jan 26 '26 23:01

Guerric P



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!