1

I have these 3 files:

bar.js

class Bar {
    test(p) {
        console.log(p);
    }
}

module.exports = Bar;

baz.js

const Bar = require('./bar');

class Baz extends Bar {
    test2(p) {
        this.test(p);
    }
}

module.exports = Baz;

foo.js

const Baz = require('./baz');
const { test2 } = new Baz();

test2('test');

When I passed 'test' to new Baz.test2(), I expected it to pass it to it's superclass (this.test(p)) where it should log 'test'. However, it threw the error:

        this.test(p);
             ^

TypeError: Cannot read property 'test' of undefined

What am I doing wrong? Why is this undefined, I thought it should reference the class itself?

newbie
  • 1,551
  • 1
  • 11
  • 21

1 Answers1

2

test2 is used apart from it's original context (Bar instance) and should be bound to proper this.

It's impossible to say from the name if it's expected to be a callback by design. In case it is, it can be bound in constructor:

class Bar {
    constructor () {
        this.test = this.test.bind(this);
    }
    ...
}

Otherwise it can be bound in-place:

const test2 = new Baz().test2.bind(this);

test2('test');

Or just not be used separately from the context:

const baz = new Baz()

baz.test2('test');
Estus Flask
  • 206,104
  • 70
  • 425
  • 565