1

So I have a class

class A {
    test() {
        return 1;
    }
    foo() {
        return this.baz(this.bar)
    }
    bar() {
        return this.baz(this.test);
    }
    baz(f){
        return f(); 
    }
}

And when I call the method foo

var a = new A();
a.foo();

I get

Uncaught TypeError: Cannot read property 'baz' of undefined
    at bar (<anonymous>:9:15)
    at A.baz (<anonymous>:12:10)
    at A.foo (<anonymous>:6:15)
    at <anonymous>:1:3

How appears that this becomes undefined after method f() is being called, and how can I fix this?

ishidex2
  • 628
  • 9
  • 11
  • 2
    Ultimately it becomes something like: `var bar = a.bar; bar();` So, `this` will be undefined. Example 3 from the accepted answer: [How does the “this” keyword work?](https://stackoverflow.com/questions/3127429) – adiga Oct 24 '19 at 09:21

3 Answers3

1

By doing that:

return this.baz(this.bar)

you are just passing a function without specifying what this its this refers to (without its context). So ultimately, when you enter the baz(f) method, you get a function as a parameter, not method of the class A. So its this is undefined. To fix it, you have two options, first is to change the foo() method:

foo() {
    return this.baz(this.bar.bind(this))
}

and a second is to change the baz(f) method:

baz(f){
    return f.call(this); 
}

Both solutions will work in this case. Hope it helps

Sebastian Kaczmarek
  • 7,135
  • 4
  • 17
  • 36
0

It was never defined. You call function without context - so does not have "this"

this.apply(f) would bind it to object

Konstantin Pribluda
  • 12,042
  • 1
  • 26
  • 34
0

You can also use arrow function to solve this problem.

class A {
    test =()=> {
        return 1;
    }
    foo=()=> {
        return this.baz(this.bar)
    }
    bar=()=> {
        return this.baz(this.test);
    }
    baz=(f)=>{
        return f(); 
    }
}

const a = new A()
console.log(a.foo())