为什么在调试器中未定义“ this”,但在console.log中可打印?

时间:2018-07-23 02:39:27

标签: javascript angular scope

console.log语句上设置断点时,为什么在调试器中未定义this,但是打印该语句没有问题?我在这里是否涉及范围?

export class OptionsSidebarComponent {

  ... 

  public filters: Object = new Object();

  ... 

  public generateFilters() {
    for (let property in this.terms) {
      if (this.terms.hasOwnProperty(property) && this.terms[property] !== null) {

        if (!this.filters.hasOwnProperty(this.productGroup.id)){
          this.filters[this.productGroup.id] = new Filters();
        }

        this.terms[property].forEach((term) => {
          console.log(this.filters);
        });
      }
    }
  }
}

2 个答案:

答案 0 :(得分:2)

使用typescript调试时,请记住,编译器可以重命名变量。在控制台中使用不带重命名的源映射的原始名称将显示未定义,即使原始值不是。确保您在监视或控制台命令中使用了已转换的名称。

答案 1 :(得分:0)

当您在自己的类中使用console.log语句引用this时,您正在其相关范围内使用它。根据您使用的框架,使用不同的术语来引用您的类... AngularJS使用$scope-Angular 2+使用this引用当前类(或当前作用域/上下文)。 / p>

在调试器中使用this时,您在其范围之外使用它。它不再引用您想要的类。

Angular中的每个组件都使用this来引用自己。这是一篇文章,需要进一步详细说明:https://angular-2-training-book.rangle.io/handout/features/refresher_on_this.html

如果我们将其简化为基本的javascript并将您的类视为一个函数,那么一个很好的例子就是:

function example(){
    var anything = 10;
    console.log(anything); //output: 10
}

console.log(anything); //undefined! we're out of scope :)

因此,从这个角度来看,this并不神奇。它只是由Angular提供给我们的,目的是使我们对组件内部其他内容的引用更加容易。