-1

The variable is pointing to an instance of an object created via function contructor. However, when I try to call its methods inside of a ternary operator, interpreter says that the variable isn't defined. (Please, omit the fact that methods will lose context, I know that)

I've noticed, that declaring a variable via "var" statement, solves the problem, but I don't understand why.

class Person {
  constructor(name) {
    this.name = name
  }

  say() {
    console.log('Hello, my name is ' + this.name)
  }

  justName() {
    console.log(this.name)
  }
}

let pers = new Person('Max')

(false ? pers.say : pers.justName)() // ReferenceError: pers is not defined
Nick Parsons
  • 31,322
  • 6
  • 25
  • 44
  • 4
    You forgot a semicolon (or few), don't rely on ASI unless you're *sure* of what you're doing (and even then, it's probably not a good idea) – CertainPerformance Jul 10 '19 at 11:23
  • 1
    What are you trying to do in the last line? you are not calling the methods and the inline if/else will always evaluate to false. If you just call the methods after the person is created the code should work just fine. – Janis Jansen Jul 10 '19 at 11:27
  • @CertainPerformance Oh, I forgot about that. Thank you! – Nothing ToSee Jul 10 '19 at 12:45
  • @Carnageous It is not a production code but a snippet for a test interview to check the understanding of loosing 'this' context. – Nothing ToSee Jul 10 '19 at 12:49

0 Answers0