0

I am kinda new using javascript and I have this problem ..

In this IIFE

(function () {

this.something = "something"; // error - this is undefined 

let loader = PIXI.loader;
    loader.add('ace', "assets/spritesData.json");
    loader.on('complete', onAssetsLoaded);
    loader.load();


function onAssetsLoaded(){
    this.gameSettings = GameSettings.getInstance();

    createrenderer();
    let rootView = new RootView(this._stage),
        rootController = new RootController(rootView,this.gameSettings);

    animate();
}
})();

Why "this" is undefined ? From what I know till now "this" right now this should be the current scope of the function ( in this case the anon function ) ?

Thanks in advance for the help.

Yordan Kanchelov
  • 511
  • 9
  • 26
  • 1
    I'm not sure why it's throwing that error, but just FYI - `this` will refer to the global context (e.g. `window`) in your code, not the function context (you would need to use `new ...` instantiation to have it refer to the function) – Rob M. Sep 02 '16 at 16:35
  • 1
    @RobM. — It would hold the global context in non-strict mode, but Babel always operates in strict mode. – Quentin Sep 02 '16 at 16:36
  • Right . Thanks for the answer :) – Yordan Kanchelov Sep 02 '16 at 16:36

2 Answers2

1

The long explanation can be found in this question. The relevant part (which isn't mentioned in the accepted answer as far as I can see) is:

when we use strict mode, this holds the value of undefined in global functions and in anonymous functions that are not bound to any object

Community
  • 1
  • 1
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
1

this usually refers to the calling object, but your function is anonymous and invoked directly. Here is how you can create new contexts:

  • the new keyword, will create a new this context and return it.

    function Constructor() { this.property = "a"; };
    let instance = new Constructor();
    // instance.property is now "a"
    
  • function.bind({}) will wrap the function so when it is invoked, this will refer to {}. function.apply works similarly, but immediately invokes the function and requires you to specify the arguments too.

  • For advanced users: Object.create

Aurelia
  • 1,052
  • 6
  • 28