javascript可以在调用者之后定义被调用者,它是如何解析的?

Sam*_*Sam 2 javascript

我想知道javascript怎么做呢?可以在调用者调用函数后定义该函数.

有没有文件可以解释它是如何工作的?

谢谢

Sud*_*oti 6

那是因为功能声明提升.所有函数声明都被提升到包含范围的顶部.函数声明看起来像:

function functionName(arg1, arg2){
    ..code here
}
Run Code Online (Sandbox Code Playgroud)

这就是你可以在代码中实际声明之前调用函数的原因.

但请注意,函数表达式不会被挂起.所以不会挂起以下内容:

var functionName = function(arg1, arg2){
    ..code here
};
Run Code Online (Sandbox Code Playgroud)

所以下面会抛出错误:

functionName(); //TypeError, undefined is not a function!
var functionName = function(arg1, arg2) {
    console.log(arg1);
};
Run Code Online (Sandbox Code Playgroud)

添加:: 考虑函数表达式的示例::

saySomething(); //You get error here
var saySomething = function() {
    console.log("Hi there!");
};
Run Code Online (Sandbox Code Playgroud)

这将不起作用并抛出错误,因为,变量声明和函数声明被提升,但在上面的函数表达式示例中,它的变量声明和赋值.变量声明被提升,但赋值保持不变.结果如下:

var saySomething;
saySomething(); //you get error here, which should be clear now as why you get the error
saySomething = function() {
    console.log("Hi there!");
};
Run Code Online (Sandbox Code Playgroud)