首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >未捕获(在promise中) TypeError: this.getChildrem不是一个函数

未捕获(在promise中) TypeError: this.getChildrem不是一个函数
EN

Stack Overflow用户
提问于 2021-11-12 17:44:10
回答 2查看 54关注 0票数 0

我有以下几点:

代码语言:javascript
复制
getitem: function(){
    $this.users = $data.data;
    $this.users = $this.users.filter( function(item) {
    if(item.status === true ) { 
        if( item.children.length > 0 ){
            item.children = this.getChildrem(item.children, true);
        }
        return item;
    }}); 
},
getChildrem: function(node, estatus){
    $children = node.filter( function(item) {
    if(item.status === estatus ) {              
        if( item.children.length > 0 ){
            item.children = this.getChildrem(item.children, estatus);
        }
        return item;
    }});       
    return $children;    
},

这是一个简单的函数递归,我只是得到了状态为‘true’的所有项(父项和子项),但我遇到了这个错误:

代码语言:javascript
复制
Uncaught (in promise) TypeError: this.getChildrem is not a function

为什么我收到这个错误?

EN

回答 2

Stack Overflow用户

发布于 2021-11-12 17:48:38

当您定义传递到node.filter中的函数时,this上下文将发生变化。您可以通过传入箭头函数或使用.bind来避免这种情况。

因此,不是

代码语言:javascript
复制
getChildrem: function(node, estatus){
    $children = node.filter( function(item) {

试试这个:

代码语言:javascript
复制
getChildrem: function(node, estatus){
    $children = node.filter( (item) => {
票数 1
EN

Stack Overflow用户

发布于 2021-11-12 18:04:30

这是因为回调函数使用的是全局作用域,而该对象在不同的作用域中

代码语言:javascript
复制
var obj = {
  test(){
    (function(){console.log(this);})(); //Prints global object
    (()=>{console.log(this);})(); // prints local object
  }
}

您需要将该普通函数更改为箭头函数,因为箭头函数将捕获封闭范围

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69947041

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档