mdn / learning-area

GitHub repo for the MDN Learning Area.
https://developer.mozilla.org/en-US/Learn
Creative Commons Zero v1.0 Universal
7.02k stars 27.01k forks source link

Problem with Inheritance in JavaScript code example. #37

Closed bluevoxInc closed 7 years ago

bluevoxInc commented 7 years ago

I am following the instructions for Inheritance in JavaScript. When I add the line:

Teacher.prototype = Object.create(Person.prototype);

to my code and attempt to validate using Object.getOwnPropertyNames(Teacher.prototype) I do not see the functions listed on the prototype. Furthermore, when I attempt to run Person.prototype.greeting() or Teacher.prototype.greeting() I get an error referencing this on line 84.

Cannot read property 'first' of undefined at Object.Person.greeting (oojs-class-inheritance-start.html:84) at :1:18

This also happens when I try the same with the finished version of this code.

It appears to be a scoping issue but I am too new to javascript just yet to analyze what is going wrong.

Thanks.

chrisdavidmills commented 7 years ago

Hi there,

It sounds to me like there is some kind of error in your code. Either you have misread an instruction, or made a typo. It is useful for me to explore what went wrong, as there is always scope for me to make my instructions clearer.

So, first of all, check your code against the finished version on our repo:

I've tried running

Teacher.prototype = Object.create(Person.prototype);

in the console on this page, and it works as expected. Also, the functions are contained on the prototype inside properties, rather than being hung off the prototype directly, so you'll have more luck with Person.prototype.greeting and Teacher.prototype.greeting (no parentheses).

If you still have trouble, feel free to throw me your code source, and I'll have a look and see what the trouble is.

bluevoxInc commented 7 years ago

I tried both the source code and live versions in Firefox and Chrome browsers. When I run: Object.getOwnPropertyNames(Teacher.prototype); I only see: Array [ "constructor", "greeting" ]

But I can query all the function definitions when I make the calls without parenthesis. In retrospect, I guess it doesn't make sense to execute a function against its prototype, only on its instance. Tried this on teacher1 and everything worked fine.

Thanks for your help!