How can javascript object method refer to variable that is not declared yet?

3783 views javascript
4

I'm reading this js tutorial, in Def. 5: Class section there's a code snippet:

// Generic prototype for all letters.
let letter = {
  getNumber() {
    return this.number;
  }
};

I wonder how can getNumber method refer to number which is not declared?

answered question

2 Answers

2

In your code, this.number is letter.number which is not defined. And, it means it is evaluted as undefined.

var obj = {};
obj.number; // undefined

posted this
4

number isn't a variable, it's a property. You don't have to declare properties (in fact, until the class fields proposal progresses, you can't declare properties; there's no property declaration syntax). Variables are storage outside of an object. A property is storage within an object.

If you're wondering how getNumber can use the property before it's created, it's because that's just how JavaScript is defined: Trying to get the value of a property that doesn't exist results in the value undefined, not an error.

posted this

Have an answer?

JD

Please login first before posting an answer.