A simple JavaScript function with an immediate call does not work ... why?

Can someone explain why this works:

var sayHello = function (name) {
   alert("Hello there " + name + "!");
}("Mike");

So far this is not the case:

function sayHello (name) {
   alert("Hello there " + name + "!");
}("Mike");

Mike Cake

+3
source share
6 answers

All you need to understand is the difference between FunctionExpressions and FunctionDeclarations in Javascript.

When you surround a function with parentheses -

(function sayHello (name) {
   alert("Hello there " + name + "!");
})("Mike");

- you, technically, apply a grouping operator to it. After application, the general production is no longer a FunctionDeclarataion, but a FunctionExpression. Compare -

function foo(){ } // FunctionDeclaration

(function foo(){ }); // FunctionExpresson
typeof function(){ }; // FunctionExpression
new function(){ }; // FunctionExpression

FunctionExpression ( FunctionDeclaration), MemberExpresson, Arguments ( "(" ")" ) . , .

, FunctionExpressions ( FunctionDeclarations, ), "sayHello" -

(function(){
  alert('...');
});

, .

+13

:

function sayHello (name) {
   alert("Hello there " + name + "!");
}

("Mike");

, "sayHello", "":

("Mike");

.

+4

:

    (function sayHello (name) {
        alert("Hello there " + name + "!");
     })("Mike");

, parens . "sayHello", . ? . , , wrapping(), sayHello, , .

+3
var sayHello = function (name) {
   alert("Hello there " + name + "!");
}("Mike");

"". sayHello.

function sayHello (name) {
   alert("Hello there " + name + "!");
}("Mike");

sayHello, }. ( "" ), , .

+1

, :

, ( "Mike" ) , . , , :

(function sayHello (name) {
   alert("Hello there " + name + "!");
})('Mike');
0

() :

(function sayHello(name) {
   alert("Hello there " + name + "!");
})("Mike");

// however -- 
alert(typeof sayHello);  // undefined

So, if you want to do something like this - you can just make it an anonymous function:

(function(name) {
   alert("Hello there " + name + "!");
})("Mike");

And I'm not sure if this is necessary, but for safety - anytime I use closure, I always wrap it in ()

0
source

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


All Articles