Javascript literal object and self-executing functions

I study object literals and self-executing functions in Javascript. After looking at some YUI code, I came across some object literal methods that execute themselves. My question is why the following code does not warn “Ohai Mark!”;

var bar = { alert: function () { window.alert('Ohai Mark!'); }, init: (function () { bar.alert(); }()) }; 
+6
source share
2 answers

More details:

 > var bar = { 

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

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

a value will be assigned after , the expression on the right side is calculated. During this assessment, the bar has any value that it had on reaching the statement (the entire line). It is currently undefined, and therefore it does not yet have a warning property.

 > }; 
+8
source

When executing the code, the bar is defined, but the resultant JSON object is not yet assigned at the point where the init () method is defined (and must be assigned to the bar object) [EDITED] . Since function-function-function is defined correctly, I would declare the function there, for example:

 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 is akin to:

 (function() { var c = c + 1; })(); 
+3
source

Source: https://habr.com/ru/post/892456/


All Articles