这个函数在 JavaScript 中是如何爬上原型链的?

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

这是一门课程的练习,其中创建了一个函数来模拟如何从对象中检索属性,因此您可以更好地了解正在发生的事情。

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);
  }
};

我的问题是else if... 我认为它是在说“如果这个对象有一个 __proto__ 属性,return DOT 函数再次但这次使用 obj.__proto__ 作为第一个值。这实际上是在做obj.__proto__.__proto__.__proto__ 递归直到找到 属性?

好吧,正如@georg 简单回答的那样:"The answer is yes".

如果我必须以此为基础进行开发,您的递归函数实际上将 return 两个值:属性 的值或 undefined.

因为隐含地,如果 属性 不在原链中,那么 if/else 将不会 return,函数将 return 没有什么默认为 returning undefined.

HTH ☺