简体   繁体   English

如何覆盖Javascript中的函数提升?

[英]How to override function hoisting in Javascript?

Isn't function abc() hoisted ? 函数abc()是否未hoisted Assuming var abc and function abc both are hoisted which would take precedence? 假设var abcfunction abc都被提升,哪个优先?

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

abc();

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

Why does the following code shows error "abc is not a function"? 为什么以下代码显示错误“ abc不是函数”?

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. 这是因为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. 它的基本含义是,如果您在代码中向下定义一个函数,则Javascript在解析代码并假定它在范围中的上方时会找到它。 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 . 但是,您已经通过显式定义abc覆盖了该功能。 Therefore it is executed assuming that abc is the variable you defined. 因此,假定abc是您定义的变量来执行。 It won't even work if you call abc() after you define the function: 如果在定义函数后调用abc() ,它将甚至无法工作:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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