2

我想知道javascript如何做到这一点?该函数可以在调用者调用该函数后定义。

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

谢谢

4

2 回答 2

6

那是因为函数声明提升。所有函数声明都被提升到包含范围的顶部。函数声明如下所示:

function functionName(arg1, arg2){
    ..code here
}

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

但请注意,函数表达式不会被提升。所以以下没有被提升:

var functionName = function(arg1, arg2){
    ..code here
};

所以下面会抛出错误:

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

补充:: 考虑一个函数表达式的例子::

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

这将不起作用并引发错误,因为变量声明和函数声明被提升,但在上面的函数表达式示例中,它的变量声明和赋值。变量声明被提升,但赋值仍然在原处。所以结果会是这样的:

var saySomething;
saySomething(); //you get error here, which should be clear now as why you get the error
saySomething = function() {
    console.log("Hi there!");
};
于 2013-08-27T03:59:41.350 回答
3

这叫做“吊装”。这篇文章解释得很好: http: //www.adequatelygood.com/JavaScript-Scoping-and-Hoisting.html

基本上发生的事情是第一个代码片段被视为第二个:

a();
function a(){};

变成

var a = function a(){};
a();
于 2013-08-27T03:49:32.070 回答