Search code examples
javascriptangularhoisting

Angular 2+ variable hoisting?


How does Angular resolve all it's variables regardless of where there placed in a component?

For example in Vanilla JS

console.log(a) // undefined
let a = 'Hello;

Angular component

ngOnInit(){
this.example()
}

example(){
console.log(this.a) // Hello
}

a = 'Hello'

I'm aware that this is bad practice and the compiler will complain about that placement of the variable but none the less I am curious how Angular achieves this, or whether it's not an Angular specific behaviour?


Solution

  • This is not an Angular behavior. Actually the piece of code that you provided is inside a class, and the a is not a variable, actually it's a property.

    JavaScript (and Typescript) doesn't requires properties to be declared before methods (neither constructor), since it's just a declaration that will be used futurely when this class will be instantiated.

    Although tslint may warn you about the placement of it after methods, it's just a coding style concern.

    You may translate a class to a traditional function constructor:

    class Car {
      make = 'default';
    
      drive() {
         /* ... */
      }
    
      model = 'foo'
    }
    

    can be wrote as (and is converted to when using some polyfill on browsers that doesn't support ES6 Class):

    var Car = function() {
      this.make = 'default';
      this.model = 'foo';
    }
    
    Car.prototype.drive = function() {
      /* ... */
    }
    

    Note that in the second case, the properties are defined inside the constructor, so it will always run before the method be called.