You-Dont-Know-JS icon indicating copy to clipboard operation
You-Dont-Know-JS copied to clipboard

What's wrong with the example in Getter & Setter section in this & Object part?

Open Kishan08 opened this issue 9 years ago • 4 comments

Currently i'm reading part 3(this & object) of YDKJS series.

Head to Chapter 3. Object, now navigate to section Getter & Setter, there's this code which is throwing: RangeError: Maximum call stack size exceeded this error and if i remove the preceding and succeeding underscore from the code. Here's the screenshot for the reference:

er

And this is your code along with underscore:

no-er

Which is running perfectly.

But you only mentioned that the underscore has no special meaning.

Then what's wrong with the code if i remove the underscore and why it's throwing RangeError??

Kishan08 avatar Feb 22 '17 07:02 Kishan08

In the first example both: getter and setter are calling itself in infinite loop. That's why getters/setters name should be different to acctual variable.

CezaryDanielNowak avatar Feb 22 '17 07:02 CezaryDanielNowak

I can't understand what you are trying to say. Can you please elaborate?

Kishan08 avatar Feb 22 '17 09:02 Kishan08

get a(){
  return this.a
}

Here is above code a is both a property, and method as getter. When this.a is called, it will redirect to this.a() which will again request this.a in the return statement.

And with later example, the _ (underscore) differentiate the property and the getter name, and hence avoids the infinite loop.

pankajpatel avatar Feb 22 '17 09:02 pankajpatel

Thanks for the suggestion.

Kishan08 avatar Feb 22 '17 17:02 Kishan08