Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript object literal and self-executing functions

Tags:

javascript

I'm studying object literals and self-executing functions in Javascript. Looking through some YUI code I came across some methods of an object literal that execute themselves. My question is why the following code does not alert 'Ohai Mark!';

var bar = {
    alert: function () {
        window.alert('Ohai Mark!');
    },
    init: (function () {
        bar.alert();
    }())
};
like image 232
dunnza Avatar asked Jul 11 '11 03:07

dunnza


2 Answers

To explain in detail:

> var bar = {

In javascript, declarations are processed first so bar exists as a variable before execution begins.

>     alert: function () {
>         window.alert('Ohai Mark!');
>     },
>     init: (function () {
>         bar.alert();
>     }())

bar will be assigned a value after the expression on the right hand side is evaluated. During that evaluation, bar has whatever value it had when the statement (the entire line) was reached. It is currently undefined, and so it does not have an alert property yet.

> };
like image 137
RobG Avatar answered Sep 28 '22 20:09

RobG


When executing the code, "bar" is defined but not yet assigned the resultant JSON object at the point which the init() method is defined (and about to assigned to the bar object) [EDITED]. As init's function-scope is properly defined, I would declare the function there, like so:

var bar = {
  init: (function () {
      var alert = function () {
        window.alert('Ohai Mark!');
      };

      alert(); //this will execute the code above
  }())
};

See Javascript Garden#namespaces and scopes. [EDIT] You might think this akin to:

(function() {
  var c = c + 1;
})();
like image 28
ghayes Avatar answered Sep 28 '22 20:09

ghayes