I want explanation on Own property and prototype properties

Tell us what’s happening:
I dont understand why the instance of the constructor doesn’t contain the prototype property, and according to the tutorial prototype properties helps in handling repeated code that the value is fixed

Your code so far

function Dog(name) {
this.name = name;

Dog.prototype.numLegs = 4;

let beagle = new Dog("Snoopy");

let ownProps = [];
let prototypeProps = [];

// Only change code below this line
for(let property in beagle){

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.193 Safari/537.36.

Challenge: Iterate Over All Properties

Link to the challenge:

Hi @CodebanK.
Yes the instance of the constructor doesn’t have the property which was defined on its prototype but has access to it. I believe what you want to see is ownProps having both name and numLegs because essentially the instance beagle “inherits” from its prototype. I am afraid that is not how prototypal inheritance works.

The first thing the JavaScript engine does after you the programmer references a property defined on a protoype object via an instance like beagle.numLegs is to check whether beagle has a numLegs property defined on it. If it does, it returns the value of that property. If it doesn’t have a property named numLegs, it checks in beagle's protoype object. If beagle's prototype object has that property it returns the value otherwise it checks in protoype object of beagle's protoype object. Yes prototypes also have prototypes. The process continues up the prototype chain. The properties defined on a prototype are not copied to an instance (that is why you don’t see those properties if you console.log an instance ) but the instances are only able to access the properties by traversing along the prototype chain as described above.

You can read more about prototypes and prototypal inheritance in the MDN docs.

1 Like