简体   繁体   English

JS函数定义顺序

[英]JS functions definitions order

Very quick question as I am having some kind of strange bugs and I can't find any documentation on this. 很快的问题,因为我遇到了一些奇怪的错误,并且我找不到任何文档。 Does order in which functions are defined in a file matter? 文件中定义功能的顺序是否重要?

For example: 例如:

function a() {
  b(); //defined below the current function
}

function b() {
  //do something
}

Is it considered proper or do I have to mind the order? 它被认为是正确的还是我必须介意订购?

Due to variable hoisting, "var statements and function declarations will be moved to the top of their enclosing scope" [1]. 由于变量吊起,“ var语句和函数声明将移至其封闭范围的顶部” [1]。

This can cause gotchas at times, but as long as the file containing the function is loaded, the order shouldn't matter. 这有时可能会引起麻烦,但是只要加载了包含该函数的文件,顺序就无关紧要。

[1] http://bonsaiden.github.io/JavaScript-Garden/#function.scopes , http://www.adequatelygood.com/JavaScript-Scoping-and-Hoisting.html [1] http://bonsaiden.github.io/JavaScript-Garden/#function.scopeshttp://www.adequatelygood.com/JavaScript-Scoping-and-Hoisting.html

在JavaScript中,只要被调用函数存在,创建函数的顺序就无关紧要。

The problem you're running into is variable hoisting. 您遇到的问题是可变吊装。 Read more about that here 在这里阅读更多关于

It is considered improper to do that according to Crockford's JSLint. 克罗克福德的JSLint认为这样做是不适当的。 However, it shouldn't matter as long as you are defining the functions in that manner. 但是,只要您以这种方式定义函数就没有关系。 For example, your code will work, but something like 例如,您的代码可以运行,但是类似

function a(){
   b();
}
function b(){
   //do something
}

will work, but 会工作,但是

function a(){
    b();
}
var b=function(){//do something};

will not work. 不管用。

So basically, if everything is loaded before you call it, you should be fine. 因此,基本上,如果在调用之前已加载所有内容,则应该没问题。 Consider wrapping it in a $("window").load() 考虑将其包装在$("window").load()

No, it does not matter, where function is. 不,没关系,函数在哪里。 It can be at top of file, at bottom of file even in another file. 它可以位于文件顶部,甚至可以位于另一个文件底部。 what matter is existence. 什么是存在。

Once JavaScript is loaded it will treated as single file or script; 加载JavaScript后,它将被视为单个文件或脚本; that is the reason you may not have function with same signature even on two different script file using on same page. 这就是为什么即使在同一页面上使用两个不同的脚本文件也可能没有相同签名的功能的原因。

Fiddle with both cases 两种情况都摆弄

a();
c();

function a() {
    b(); //defined below the current function
}

function b() {
    alert("called b");
}

function c() {
    b();//defined above the current function
}

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

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