Answer the question
In order to leave comments, you need to log in
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'));
Answer the question
In order to leave comments, you need to log in
(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("привет","мир");
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.
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');
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))
(function($) {
/* code */
} )(jQuery)
!function($) {
/* code */
}(jQuery)
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 questionAsk a Question
731 491 924 answers to any question