V
V
Vetal Matitskiy2014-12-10 09:54:43
JavaScript
Vetal Matitskiy, 2014-12-10 09:54:43

How to understand code snippet of view (function(){}()) in js?

How to understand the code fragment of the view (function(){}())
Good afternoon, dear js-gurus, while
analyzing the api of one of the libraries in the example, I found a view construct:

(function(d, s, id){
    op1;
    op2;
   ...
}(document, 'script', 'jssdk'));

tell me, please, what is going on here, why do the brackets wrap around the function definition and what is the sequence at the end of "(document, 'script', 'jssdk')"
and a more general question, are there any tools that help to understand encrypted constructions of this kind?

Answer the question

In order to leave comments, you need to log in

5 answer(s)
T
TekVanDo, 2014-12-10
@TekVanDo

(function(){})() - immediately calls the function, i.e. the code is equivalent to:

(function(ss,mm){
    console.log(ss,mm);
})("привет","мир");

function test(ss,mm){
    console.log(ss,mm);
}

test("привет","мир");

M
myrslok, 2014-12-10
@myrslok

This is called immediately-invoked function expression , meaning that in JavaScript functions create a scope, and blocks do not create with all the ensuing consequences. By the way, if it is not clear what these consequences are, perhaps you should familiarize yourself with scopes (English -- scope) in more detail. Briefly, you can see the link, but in general this is a very important topic.

N
Nicholas Kim, 2014-12-10
@Yaruson

If I'm not mistaken, it's just an unnamed function with a call. Can be read as

function fx(d, s, id) { ... }
fx(document, 'script', 'jssdk');

As far as I understand, this technique is used to wrap variables in a scope, since in js the only scope is a function. Knowledgeable people, please correct me if I'm wrong :-)

O
Oogway, 2014-12-10
@Oogway

I can add that the brackets wrapping the function are needed so that the interpreter perceives it as an expression, the second pair of brackets is the call expression.

(function($) {
  /* code */
} (jQuery))

You can find this entry:
(function($) {
  /* code */
} )(jQuery)

Or:
!function($) {
  /* code */
}(jQuery)

Well, other unary operators: ~, +, - if the function does not return anything. You can also use the expression molestation. As parameters, they usually pass references to the global objects window, jQuery, etc.

B
Bhudh, 2014-12-10
@Bhudh

This is not a function definition.
This is a function expression with an immediate call.
The sequence at the end is the usual parameters when called.
There are tools to help you understand. Books on JavaScript syntax, for example.
Best of all Douglas Crockford and David Flanagan.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question