0

I'm new to JavaScript, I'm wondering why the following throws an error in validateThisScenario and what I can do to make it work in a similar structure.

class TestClass {
  // ...

  getResponse() {
    return this._response
  }

  validateThisScenario() {
    const response = this.getResponse() // TypeError: Cannot read property 'getResponse' of undefined
  }

  test1() {
    return this.test(this.validateThisScenario)
  }

  test(validation) {
  return Promise.resolve()
    .then(() => validation())
    .catch((err => {
        // ...
    }))
  }
}
Robin
  • 25
  • 1
  • 7
  • 1
    When in doubt console.log (or breakpoint) - observe what `this` is - is it what you expected it to be (the class instance)? – Dominic Oct 14 '19 at 21:26
  • it looks like your code works if you call `validateThisScenario` directly, but not if you call `test1`. Try replacing the method call in `test1` with `this.test(this.validateThisScenario.bind(this))`. Also see the MDN page: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_objects/Function/bind – Andrew Ault Oct 14 '19 at 21:30

1 Answers1

-1

The this keyword refers to an instance of the class. So you need an instance of the class in order to call the method. The exception is when a method is static.

Let's say you have a class like this:

class TestClass {
  doSomething() {
    console.log("Did something");
  }
}

In order to call the doSomething method, you need an instance of it first. i.e.

var instanceOfTestClass = new TestClass();
instanceOfTestClass.doSomething();    // OK

If you don't want to create an instance, what you need is a static method

class TestClass {
  static doSomething() {
    console.log("Did something");
  }
}

Then this is allowed:

TestClass.doSomething();  // OK
Seane
  • 41
  • 1
  • 6
  • Not quite. The problem is when doing `this.test(this.validateThisScenario)` the this will have lost its context in the `test` function. One solution could be in the test function, assign this to a variable `var test = this;` and then call `validation.call(test)` – jperl Oct 14 '19 at 21:43
  • Actually, like someone said, `this.test(this.validateThisScenario.bind(this))`is better. – jperl Oct 14 '19 at 21:48