0

I have the following example, and I want to access foo variable within the function a of my object test.

class bar {
    private foo: string = "foobar";

    constructor() { /* ... Implementation ... */ }

    fncA(): this {
        // ... implementation 
        console.log(this.foo); // this is working as expected: "foobar"
        const test = {
            "a": function() {
                // ... implementation
            },
            "b": function() {
                console.log(this.foo); // TypeError: this.foo is undefined
            }
        };
        return this;
    }
}

TypeError: this.foo is undefined

In my opinion these are some binding problems of the this variable, but I have no idea to solve this issue the right way.

I appreciate any help, thanks in advance.

Habebit
  • 957
  • 6
  • 23
  • 1
    Use an arrow function to keep `this` the same inside a function as outside it. `a: () => {`, `b: () => {` – Ry- Jul 08 '19 at 17:34

1 Answers1

1

In this particular case, you could make your functions in the test object arrow functions, so they close over this rather than having this set by how they're called:

class bar {
    private foo: string = "foobar";

    constructor() { /* ... Implementation ... */ }

    fncA(): this {
        // ... implementation 
        console.log(this.foo); // this is working as expected: "foobar"
        const test = {
            "a": () => {                // ***
                // ... implementation
            },
            "b": () => {                // ***
                console.log(this.foo);
            }
        };
        return this;
    }
}

(Note that that fixes the TypeScript error about this.foo, but nothing ever uses the test object for anything in that code.)


Side note: The overwhelming convention in JavaScript and TypeScript is that you capitalize the names of constructor functions. So class Bar, rather than class bar.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875