0

I can't understand why the following code doesn't work.

var test=null;
(function(){
 var Class=...
 test=new Class();
})();
test.doSomething();// ERROR test is null

As I know if I don't declare variable using var than js must find the variable outside current scope (function). Please, say what I'm doin wrong.

EDIT
The full code:

  var Application=null;
    require(["Aqua","$"],function(Aqua,$){
        var Class = Aqua.Application.extend();
        Application = new Class();
    }); 
Application.do("aaa");//Application is null

but the following works

  var Application=null;
    require(["Aqua","$"],function(Aqua,$){
        var Class = Aqua.Application.extend();
        Application = new Class();
        Application.do("aaa");
    }); 

2 Answers2

2

Require is an asynchronous dependency library and as such the bottom line Application.do("aaa"); is not in the callback. That bottom line is called before the require.js callback with the Application = new Class(); part has run.

You have solved it in your bottom example for this very reason.

Ted Johnson
  • 4,315
  • 3
  • 29
  • 31
  • Thank you for your time. I know that require is asynchronous library - it loads modules asynchronously. But! We do call method require(). So It must be executed first. Please,explain. –  Dec 14 '14 at 17:03
  • You call it first, but that does not mean it has completed executing, it can happen in parallel. It has to go get resources asynchronously, via AJAX. More can be learned by reading about AJAX and how that works or the JavaScript event loop approach. The callback code waits on the JavaScript execution stack until Javascript completes running actively on say the lines below the require function call like your `Application.do("aaa");`. The key is that require.js is using those (AJAX and event loop) facilities under the covers to do things in 'parallel'. – Ted Johnson Dec 14 '14 at 17:09
  • Thank you for detailed explanation. I thought that require() works other way. Now I understood. –  Dec 14 '14 at 17:13
0

Maybe you are doing something wrong in the ellipsed part?

This works fine for me:

var test=null;
(function () {
    var Class = function () {
        this.doSomething = function () { console.log('hey'); }
    };
    test = new Class();
})();
test.doSomething();// prints hey

Notice you need to add the this since it is a class and you are using new

Luan Nico
  • 5,376
  • 2
  • 30
  • 60