Startup function created in two ways in javascript

var a = function(){
    alert("2");
}

function a(){
    alert("1");
}

a();
Run code

As above, I declared the two functions differently. When I started a(), I got 2. Why?

+4
source share
4 answers

When you declare a function or variable in JavaScript, it becomes β€œraised”, which means that the JavaScript interpreter pretends that the variable ( ain your case) was declared at the top of the file sphere.

When this declaration takes shape function a() ..., the definition of a function rises with the declaration.

Type tasks are a = function ()...not raised, and therefore the assignment occurs after the fragment function a() ...and redefines it.

+8
source

"" , :

// hoisted function declaration (but written as an
// assignment of a function expression to a variable)
var a = function a(){
    alert("1");
}

a = function(){
    alert("2");
}

a();

, a, 2, .

+2

: .

, , ( (2)) .

, a 2 , 1.

:

// this logs the "second" version, even though it might look like `a` was not even declared yet.
console.log('a curently:',a.toString()); 
var a = function(){
    console.log('first');
    alert("2");
}

function a(){
    console.log('second');
    alert("1");
}

a(); //calling a here logs "first" and alerts 2, as you describe.
+1

@RichieHindle , , . ( ) , function, ; , javascript.

, :

var a;
function a(){ 
    alert("1");
}
a = function(){
    alert("2");
}

a();  // alerts "2"

- , , a a, . , Javascript . - Javascript .

This is why many JavaScript developers and style guides suggest declaring your variables at the top of the field and not rely on the side effects of lifting, as you (or someone else working on your code) may be in the shadow and re-assigning the variable, previously announced in the same area.

0
source

All Articles