JavaScript 中代码的执行顺序是什么?
JavaScript 中的代码到底是如何执行的?我的意思是按什么顺序?如果我声明这样的函数,执行顺序是否会有所不同:
function render() {
// Code here
}
而不是这样:
var render = new function(){
// Same code here
}
JavaScript 是否执行脚本文件中定义的函数,无论它们是否由事件处理程序调用? (例如onload=function()
)。
最后,如果一个函数定义在另一个函数中,那么当调用父函数时,下层函数是否也会被调用?例如,
function a(){
function b(){
// code
}
function c(){
//code
}
}
我试图具体了解 JavaScript 中的执行顺序。
How exactly is code in JavaScript executed? I mean in what order? Would there be a difference in the order of execution if I declared a function like this:
function render() {
// Code here
}
instead of this:
var render = new function(){
// Same code here
}
Does JavaScript execute functions that are defined in a scripting file regardless of whether they're called by an event handler? (e.g. onload=function()
).
And finally if a function is defined in another function, when the parent function is called, is the lower function also called too? e.g.
function a(){
function b(){
// code
}
function c(){
//code
}
}
I'm trying to get a concrete understanding of order of execution in JavaScript.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
new
关键字不会创建新函数。它通过运行该函数创建一个新对象。因此,这实际上会运行方法的主体并返回一个对象。如果您询问函数何时解析并将其添加到作用域,那么这是特定于实现的,但所有函数都被提升到作用域的顶部,并且通常在执行任何代码之前进行解析。
函数仅在您通过调用
f()
调用函数时执行The
new
keyword doesn't create a new Function. It creates a new object by running the function. So this would actually run the body of the method and return an object instead.If your asking when are functions parsed and added to scope then that's implementation specific, but all functions are hoisted to the top of scope and generally parsed before any code is executed.
Functions are only executed when you call them by invoking
f()
函数声明被提升(因此可以在定义它之前在代码中调用它),而函数语句则不是。
函数在被调用时就被调用。要么是因为某些东西有
theFunction
后跟()
(可能带有参数),要么是因为它已成为事件处理程序。如果是 JS,那么它会将一个字符串分配给需要函数的东西。如果是 HTML,那么您需要
()
来调用该函数。不会。函数仅在被调用时才被调用。在另一个函数中声明一个函数只会限制其范围。
A function declaration is hoisted (so it can be called earlier in the code then it is defined), a function statement isn't.
A function is called when it is called. Either because something has
theFunction
followed by()
(possibly with arguments) or because it has been made an event handler.If that is JS, then it will assign a string to something expecting a function. If that is HTML, then you need
()
to call the function.No. A function is only called when it is called. Declaring a function inside another one just limits its scope.
当您声明一个函数时,它在被调用之前不会执行(对于 onload 和其他事件中声明的函数也是如此)。
对于嵌套函数,当调用顶级函数时,它们不会自动执行,直到包含函数调用它们。
When you declare a function, it is not executed until it's called (that's true for ones declared in onload and other events as well).
For nested functions, they are not executed automatically when the top-level function is called UNTIL the containing function calls them.