Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
        });
      }
    }
  }
}
like image 669
thatvegandev Avatar asked Jul 23 '18 02:07

thatvegandev


2 Answers

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.

like image 155
Sajeetharan Avatar answered Nov 15 '22 04:11

Sajeetharan


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.

like image 27
Kyle Burkett Avatar answered Nov 15 '22 06:11

Kyle Burkett