-2

Why is the following throwing an error, and how would I go about trying to fix.

class Foo {
  bar() {
   console.log("bar"); 
  }
  fizz() {
   this.bar(); // TypeError: this is undefined
  }
}

let foo = new Foo();
let buzz = foo.fizz;
buzz();
grahamcracker1234
  • 591
  • 1
  • 7
  • 27

1 Answers1

1

Use arrow function:

class Foo {
  bar() {
   console.log("bar"); 
  }
  fizz=()=> {
   this.bar(); // TypeError: this is undefined
  }
}

let foo = new Foo();
let buzz = foo.fizz;
buzz();
Sunil Lama
  • 4,531
  • 1
  • 18
  • 46
  • This requires _very_ modern browsers to work since it's only been introduced in ES9 – volt Feb 25 '20 at 19:06
  • @volt, what are you saying, the class and arrow function concept was there from es6, 2015 – Sunil Lama Feb 25 '20 at 19:08
  • 1
    Correct, but that's not what you're using here. Your code relies on [class fields](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/Class_fields) not just classes and arrow functions. – volt Feb 25 '20 at 19:11
  • the OP is asking why the this keyword is throwing error when he is not directly calling the function, it has nothing to do with the modern browserrs? – Sunil Lama Feb 25 '20 at 19:18
  • @volt what does the browser support look like for this feature? – grahamcracker1234 Feb 25 '20 at 19:22
  • @grahamcracker1234 For popular browsers, MDN says it only works on Chrome (74+) but in my testing It works on the latest Chrome, Firefox and Chromium Edge but results in errors on Safari, IE11, and old Edge. – volt Feb 25 '20 at 19:34
  • I think there's a misunderstanding here @SunilLama. Your example defines `fizz` as a class field / property not as a method of the `Foo` class. That's what's not supported. – volt Feb 25 '20 at 19:37