Search code examples
javascriptprototypeprototypal-inheritance

How is this function climbing up the prototype chain in JavaScript?


This is an exercise from a course, which has one create a function to simulate how properties are retrieved from objects, so you get a better idea what is happening.

DOT = function dotFunc(obj, prop){
  // if this obj has this property just return it
  if(obj.hasOwnProperty(prop)){
      return obj[prop];

  // otherwise keep waking up the proto chain
  } else if (obj.__proto__){
      return DOT(obj.__proto__, prop);
  }
};

My problem is with the else if... I take it to be saying "If this object has a __proto__ property, return the DOT function again but this time using obj.__proto__ as the first value. Is this essentially doing obj.__proto__.__proto__.__proto__ recursively until it finds the property?


Solution

  • well, as @georg simply answered: "The answer is yes".

    If I had to develop on that, your recursive function will actually return two values: either the property's value or undefined.

    Because implicitly, if the property is not in the proto chain, then the if/else will not return, and the function will return nothing which defaults to returning undefined.

    HTH ☺