简体   繁体   English

函数声明未定义-为什么?

[英]Function declaration undefined - Why?

I got a fairly standard init function passed to a variable. 我有一个相当标准的初始化函数传递给变量。

var initFunction = function()... var initFunction = function()...

It's the same like "function initFunction(){}", isn't it? 就像“ function initFunction(){}”一样,不是吗? (internal, JavaScript creates a variable as well) (内部,JavaScript也会创建一个变量)

If I declare a function variable in my init function, and call it before it's declaration, it must be accessible due to the fact that all definitions (var's) in a function are initialized at first. 如果我在init函数中声明了一个函数变量,并在声明之前对其进行了调用,则由于必须首先初始化函数中的所有定义(变量),因此必须可以访问它。 That's what I thought is in JS's nature. 我认为这就是JS的本质。

The following code doesn't work (innerFunction is undefined) 以下代码不起作用(innerFunction未定义)

var initFunction = function(){
    if(0 == 0){
        innerFunction();
    }
    var innerFunction = function(){
        alert("Hello World");
    };
};

initFunction();

By the way: Is it good practice to close all function's with a semicolon? 顺便说一句:用分号关闭所有函数是一种好习惯吗?

Best regards 最好的祝福

The problem here is called Variable Hoisting . 这里的问题称为可变提升 When you do: 当您这样做时:

var innerFunction = function(){
    alert("Hello World");
};

The calling time will have: 通话时间为:

var innerFunction = null; // Or undefined may be.

Then after the definition, it gets defined. 然后,在定义之后,将其定义。 Whereas, when you replace your code with: 而当您将代码替换为:

if (0 == 0) {
    innerFunction();
}
function innerFunction() {
    alert("Hello World");
} // Notice no semi colon.

The whole function gets defined in the first place. 整个功能首先定义。 If you wanna use function expressions, and not declarations, you need to take the definition to the top of the call. 如果要使用函数表达式而不是声明,则需要将定义放在调用的顶部。

Now this would work. 现在,这将起作用。

var initFunction = function(){
    var innerFunction = function(){
        alert("Hello World");
    };
    if (0 == 0) {
        innerFunction();
    }
};

Is it good practice to close all function's with a semicolon? 用分号关闭所有函数是一种好习惯吗?

For function expressions, yes it is a good practise. 对于函数表达式, 是的,这是一个很好的实践。 For normal function declarations (using function keyword and not an anonymous function), it is not necessary. 对于普通的函数声明(使用function关键字而不是匿名函数),没有必要。

It's the same like "function initFunction(){}", isn't it? 就像“ function initFunction(){}”一样,不是吗? (

No. Function declarations are hoisted. 否。函数声明被吊起。 Function expressions are not. 函数表达式不是。 (You have a function expression). (您有一个函数表达式)。

You try to call innerFunction(); 您尝试调用innerFunction(); before a value is assigned to innerFunction (two lines later). 在将值分配给innerFunction (两行之后)。

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

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