【问题标题】:Using a method as callback function for a filter affects scope of the callback使用方法作为过滤器的回调函数会影响回调的范围
【发布时间】:2020-05-17 12:13:23
【问题描述】:

我在 Angular 中遇到了一个问题,我的方法因被称为回调函数而失去了作用域。谁能解释为什么this 更改为undefined

@Component({...})
export class SomeClass {
  public status = 'any';

  public filter_account_accesses() {
    console.log( this.status );
    let account_accesses = [...];
    return account_accesses.filter( this.status_filter )
  }
  private status_filter( account_access ): boolean {
    console.log( typeof this );
    // this is undefined!
    return true;
  }
}

PS:我已经知道我可以通过传递 this 作为参数来解决这个问题。我想知道为什么会发生范围变化。以及可选的如何防止它。

【问题讨论】:

    标签: javascript angular typescript filter


    【解决方案1】:

    函数中this 的值取决于调用该函数的方式。我们来看一个简单的例子:

    function A() {}
    A.prototype.foo = function() {
      // do something
    }
    
    const a = new A();
    

    如果foo这样调用,那么里面this的值就是a对象:

    a.foo();
    

    但是,如果您将对 foo 函数的引用存储到某个其他变量,它将不再绑定到 a 实例,并且 this 的值将是未定义的:

    const f = a.foo;
    
    f(); // <- value of this inside is undefined
    

    这与您在代码 sn-p 中所做的类似:您将对实例方法 status_filter 的引用传递给过滤器函数,并且它没有绑定到您的实例,这就是为什么当 @987654331 @callback被调用this里面的值是未定义的。

    您可以使用bind 将函数绑定到您的实例:

    return account_accesses.filter( this.status_filter.bind(this) )
    

    它将创建您的函数的副本,其中this 指向您的实例。

    另外,我向您推荐这篇关于 this 如何在 JS 中工作的精彩而详尽的文章:http://dmitrysoshnikov.com/ecmascript/chapter-3-this/

    【讨论】:

      【解决方案2】:

      因为您的函数是使用数组过滤器调用的。有两种方法可以做到不丢失this

      1. 使用箭头函数
      return account_accesses.filter(value => this.status_filter(value));
      
      1. 使用bind
      return account_accesses.filter(this.status_filter.bind(this));
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-09-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多