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:
> 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.
> };
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;
})();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With