简体   繁体   中英

How to override function hoisting in Javascript?

Isn't function abc() hoisted ? Assuming var abc and function abc both are hoisted which would take precedence?

var abc = 10;
console.log(abc);

abc();

function abc(){
    console.log("abc");
}

Why does the following code shows error "abc is not a function"?

That is equivalent to writing

// hoisted stuff
var abc;
function abc(){
    console.log("abc");
}
// end hoisted stuff
// your code is now
abc = 10; // abc now no longer a function
console.log(abc);
abc();

It is because of the Function hoisting feature in Javascript. You can read more about it here . What it basically means is that if you define a function down in your code, Javascript finds it when it parses the code and assumes it is defined up there in the scope. So this code:

abc();

function abc(){
    console.log("abc");
}

Works as if you wrote:

function abc(){
    console.log("abc");
}

abc();

But you have overriden the function by explicitly defining abc . Therefore it is executed assuming that abc is the variable you defined. It won't even work if you call abc() after you define the function:

var abc = 10;
console.log(abc);

function abc(){
    console.log("abc");
}

abc(); // still an error because abc is still considered a var
console.log(abc); //prints 10

By defining a variable with the same name as the function you essentially hidden it. To solve the problem you can give them different names or use function expression (which is like assigning a new value to the variable and doesn't do hoisting):

var abc = 10;
console.log(abc); // prints 10

abc = function abc() { // you are assigning a new value to abc
    console.log("abc");
}

abc(); // prints 'abc'

Remember that when you use function expressions, the function name is only accessible inside the function body.

var a = function b() { console.log('b')}
b() // Uncaught ReferenceError: b is not defined
a() // prints 'b'

In this case the function name can however be used inside the function body for recursive calls:

function b(x) { return x > 2 ? x * b(x - 1) : 1 }
b(4); // returns 12

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM