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();
}())
};
To explain in detail:
In javascript, declarations are processed first so bar exists as a variable before execution begins.
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.