Jay Bienvenu
Jay Bienvenu

Reputation: 3293

Aurelia transpiler: "this" is "null"

I have the following code in my Aurelia app:

import {digit} from "../util/random" // generates a random digit [0,9]

export class UnitedStates {

  zipCode() {
    return ""+digit(5);
  };

  zipPlus4() {
    return this.zipCode()+"-"+digit(4);
  };

  ...

}

Getting the error TypeError: Cannot read property 'zipCode' of null on the body of zipPlus4. Inspection in the developer tool reveals that this is null.

Why is this null, and how do I fix this?

Upvotes: 1

Views: 75

Answers (1)

Matthew James Davis
Matthew James Davis

Reputation: 12295

This is an issue with the transpiler. Recall that the arrow function notation maintains lexical this (or read here for more). So, when Babel and other transpilers enter a new scope, they maintain a local this variable so that it will be accessible from any child scopes. Usually, this variable is _this.

Sometimes, debuggers like DevTools have a hard time understanding the sourcemaps, and they report a null this. Turns out, this is only when inspecting the code; when running the code, it works properly.

So how do you inspect the value of this when it is reported to be null? Inspect _this, usually from the console. That will give you the true this value that is being used.

Upvotes: 2

Related Questions