mzoz
mzoz

Reputation: 1353

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

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?

Upvotes: 0

Views: 35

Answers (2)

T.J. Crowder
T.J. Crowder

Reputation: 1074949

number isn't a variable, it's a property. You don't have to declare properties (in fact, until the class fields proposal progresses [it's currently at Stage 3], you can't declare properties; there's no property declaration syntax, just a property initialization 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.


¹ "...outside of an object." At least, as far as your code is concerned. In specification terms, variables are bindings (which are very similar to properties) within a lexical environment object, but that's a specification thing, not something you can directly use in code.

Upvotes: 2

ZeroCho
ZeroCho

Reputation: 1360

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

Upvotes: 1

Related Questions