Skip to content Skip to sidebar Skip to footer

How Do I Retrieve A Property From A Prototype's Object That Is Inside A Constructor Function

I think the question explains itself. I am trying to retrieve a specific property that is inside a prototype's object that is inside a constructor object. If I cannot retrieve it,

Solution 1:

It is quite simple, you are shadowing name with animal. Property fetching works like this. When you call obj.x it looks for property named x in obj. If it finds it, it returns value of that property, otherwise it looks for property x in constructor proptotype, if it find it it returns it. If it does not find it it looks in prototype objects constructor prototype, and so on till last prototype which is Object {}. If it does not find it, undefined is returned.

For more info look here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Inheritance_and_the_prototype_chain

So in your case, bob has property name and its value is animal. You added this property to bob when you called animal function with context set to this in Human controller.

Maybe it example will help you understand prototype chain better:

functionA() {
  this.x2 = 2;
}

A.prototype.x3 = 3;

functionB() {
  this.x1 = 1;
}
B.prototype = newA();

const b = newB();
const b2 = newB();
b2.x3 = 'something';

console.log(b.x1); //found on bconsole.log(b.x2); //found on B.prototypeconsole.log(b.x3); //found on A.prototypeconsole.log(b2.x3); //shadowed by b2.x3

Solution 2:

Why you can't retrieve a prototype's object property which has the same name as initial object's existing own property :

... When a property is read on an object, the JavaScript engine first looks for an own property with that name. If the engine finds a correctly named own property, it returns that value. If no own property with that name exists on the target object, JavaScript searches the [[Prototype]] object instead. If a prototype property with that name exists, the value of that property is returned. If the search concludes without finding a property with the correct name, undefined is returned.

from The principles of object-oriented JavaScript / by Nicholas C. Zakas

Post a Comment for "How Do I Retrieve A Property From A Prototype's Object That Is Inside A Constructor Function"