Javascript closestParent方法始终返回';未定义';

Javascript closestParent方法始终返回';未定义';,javascript,recursion,ecmascript-6,closest,Javascript,Recursion,Ecmascript 6,Closest,我很难编写一个函数(或者更具体的ES6类方法)来返回与指定选择器匹配的最接近父元素 我的函数再次递归调用自身,直到在当前元素classList属性中找到所需的类 如果我记录元素,我会得到我想要的确切元素,但是如果我记录函数调用本身,它总是返回未定义的 这是我的密码: findParent (element, selector) { if (element === document) return null // stops when at end of tree if (elem

我很难编写一个函数(或者更具体的ES6类方法)来返回与指定选择器匹配的最接近父元素

我的函数再次递归调用自身,直到在当前元素
classList
属性中找到所需的类

如果我记录元素,我会得到我想要的确切元素,但是如果我记录函数调用本身,它总是返回
未定义的

这是我的密码:

findParent (element, selector) {
    if (element === document) return null // stops when at end of tree
    if (element.classList.contains('foo-selector')) {
      console.log(element)  // logs the expected element
      return element // returns 'undefined'
    }
    this.findParent(element.parentNode) // function calls itself again
}
我做了一点实验,研究了getClosest函数的不同实现,发现了一个使用for循环的有效函数。但除此之外,它使用了一种非常相似的方法

这让我得出结论,我对递归做了一些错误的事情;我只是看不到。。。
有什么想法吗?

当您再次呼叫时,您的手机不会返回。更改如下:

findParent (element, selector) {
    if (element === document) return null // stops when at end of tree
    if (element.classList.contains('foo-selector')) {
      console.log(element)  // logs the expected element
      return element // returns 'undefined'
    }
    return this.findParent(element.parentNode) // function calls itself again
}

您需要从再次调用递归函数的位置返回

findParent (element, selector) {
    if (element === document) return null // stops when at end of tree
    if (element.classList.contains('foo-selector')) {
      console.log(element)  // logs the expected element
      return element 
    }
    return this.findParent(element.parentNode) 
}

你的递归不起作用。您既不传递参数,也不返回其结果。我必须再次向最后一行中的调用传递
选择器
,但错误在我身上;)谢谢!