What do these lines do?

I'm starting to learn javascript for a project, I found a script that does part of what I need to do, I would like to know how it works, both for me and, if necessary, for a change.

It was originally used inside the page, now I put it in a file myself and no longer work, so I split it in parts because I can’t get it all.
Here is what bothers me the most:

1) Is this a function declaration? How does is called? How can it be called?

(function() { //some code })(); 

2) I do not know what is happening here.

 var VARIABLE = VARIABLE || {}; 

3) Do I define a methodCall implementation here? Something like method overrides in Java?

 VARIABLE.methodCall = function(parameter) { console.log("parameter was: " + parameter); }; 

Thank you in advance for your help.

+4
source share
2 answers

1) creates an unnamed function and performs it. this is useful for creating scope for local variables invisible outside the function. You do not need to refer to this aside from this, the "()" at the end does this for you.

2) if the variable is null / undefined, set it to an empty object.

3) yes, this should work as you expect, you can call VARIABLE.methodCall (parameter)

in response to your comment, here is a general example

 function foo (VARIABLE) { var VARIABLE = VARIABLE || {}; } 
+10
source
 (function() { //some code })(); 

just runs //some code , but the variables will not remain in it, since the function() { } block introduces a new inner scope.

Designation

function() { } is called closure, it allows variables to be functions. For instance,

(function() { })() is a common JavaScript idiom. After ) exists () , which causes the before as function expression, so (callback || function(x) { return x; })(x) is permitted.

var a = function a() { return 1; }

var VARIABLE = VARIABLE || {}; uses a short circuit OR If VARIABLE not defined, VARIABLE will be set to {} , an empty object. (otherwise, if VARIABLE exists, it will not change)

x = A || B x = A || B means "If A evaluates to TRUE, x equals A, otherwise x equals B.".

VARIABLE.methodCall , as you said, adds methodCall to VARIABLE without deleting other values ​​in VARIABLE

+3
source

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


All Articles