简体   繁体   中英

Why is 'this' undefined in the debugger but printable in a console.log?

When setting a breakpoint on the console.log statement, why would this be undefined in the debugger but the statement print with no issues? Am I missing something in regards to scope here?

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

With typescript While debugging, keep in mind that transpilers can rename variables. Using the original name in the console without sourcemaps that include renaming will show you undefined even if the original value isn't. Make sure you use the transpiled name in watches or console commands.

When you're referencing this with your console.log statement inside its own class, you're using it in its relevant scope. Depending on the framework you are using, different terms are used to reference your class... AngularJS used $scope - Angular 2+ uses this to reference the current class (or current scope/context).

When you use this in your debugger you're using it outside of its scope. It no longer references the class you intend it to.

Each one of your components in Angular uses this to reference itself. Here's an article to explain in further detail: https://angular-2-training-book.rangle.io/handout/features/refresher_on_this.html

If we simplify it to basic javascript and look at your class as just a function a good example would be this:

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

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

So looking at it from this perspective, this is nothing magical. It's just provided to us by Angular to make our references to other things inside our components easier.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM