getify / You-Dont-Know-JS

A book series on JavaScript. @YDKJS on twitter.
Other
177.86k stars 33.39k forks source link

Ch3 "Objects-Classes" getX() should return 3, not 21 #1857

Closed TylerWoolcott closed 5 months ago

TylerWoolcott commented 5 months ago

Please type "I already searched for this issue": I already searched for this issue Edition: (pull requests not accepted for previous editions) 2nd Book Title: objects-classes Chapter: 3 Section Title: Overiding methods Topic: For the code example (below), shouldn't the result of point.printX(); be x: 3 instead? Given that Point3d is a subclass of Point2d, when Point3d is instantiated as point using the super keyword, it inherits the properties of Point2d: a. super.getX() refers to the getX() method in Point2d. b. The getX() method in Point2d returns the x property of Point2d, which is 3. c. Hence, printX() outputs x: 3.

The code example from the chapter: class Point2d { x = 3 y = 4

getX() {
    return this.x;
}

}

class Point3d extends Point2d { x = 21 y = 10 z = 5

getX() {
    return this.x * 2;
}
printX() {
    console.log(`x: ${super.getX()}`);
}

}

var point = new Point3d();

point.printX(); // x: 21

getify commented 5 months ago

I copied and pasted the code you quoted above (same as in the book chapter). Here's the output:

console-output

That's consistent with what I indicated in the chapter.

The reasoning you asserted is inaccurate: "The getX() method in Point2d returns the x property of Point2d, which is 3."

The getX() method in Point2d returns the this.x instance property, not a static property of Point2d (nor a lexical x variable). The this reference here resolves to the point object, since that's the call-site. And that object has the x value of 21 from the Point3d() constructor.


Side note: you've filed this as a PR against the issue template, as opposed to just as a normal issue. That's a confusing way to do it, so I'm going to close this. If you feel you want to discuss further, please open a new regular issue.