drupal_add_js and variables into anonymous functions, objects undefined? Pulling my hair out. Read a lot of stuff about scopechain and closure to tackle this one myself. And as i understand at some level, i can't get this to work.

I wrote a module for likebuttons (like facebook twitter etc). It's working ok, but I want to make it more generic and multilingual. I did the following. In my facebook function I have this:

&lt;?php  
  $lang = 'en_EN'; // 

  // Load javascript
  $settings['lang'] = $lang;
  drupal_add_js(array('mymodule' =&gt; $settings), 'setting');
  drupal_add_js(drupal_get_path('module', 'mymodule') . '/js/myscript.js');
?&gt;


This is working ok. The javascript gets loaded and the $settings['lang'] is passed to browser too (as I can see in chrome console it gives me 'en_EN' on Drupal.settings.mymodule.lang).

In myscript.js script I have the following (simplified to be a more generic question

(function() {

  var language = Drupal.settings.mymodule.lang;
  console.log(language); //undefined

}());


UPDATE:
So it's anonymous.... All those terms.
Ok, got the object inside now. Now i got to figure out how to get the 'en_EN' from the object.

Updated script:

(function(language) {

var my_var = language.settings.mymodule.lang;
console.log(my_var); // undefined
console.log(language); //Object { settings={...}, behaviors={...}, locale={...}, meer...}
console.log(language.settings); //Object {}
console.dir(language.settings) // There are no underlying objects
}(Drupal));


Here language contains the complete object drupal has passed. (I can see that in console).

Why can't I go in the object language like normal and get my value by using language.settings.mymodule.lang?

Seems like Drupal.settings is empty inside the anonymous function, but has all elements there in the DOM tree. I don't know what causes this to be an empty object inside an anonymous function.
As of Drupal 6 javascript is put inside function that we assign as a property of Drupal.behaviors. Example,

Drupal.behaviors.myModuleBehavior = function (context) {
  //Do some fancy stuff
};


Drupal 7.x:

Drupal.behaviors.myModuleBehavior = {
  attach: function (context, settings) {
    $('input.myCustomBehavior', context).once('myCustomBehavior', function () {
    // Apply the myCustomBehaviour effect to the elements only once.
    });
  }
};


So your code should be 

(function($) {
  Drupal.behaviors.myModuleBehavior = {
    attach: function (context, settings) {
      var my_var = Drupal.settings.mymodule.lang;
      console.log(my_var); 
      console.log(language); 
    }
  };
})(jQuery);