javascript事件循环问题
我想知道事件循环在javascript中是如何工作的, 我正在使用node.js,但我想同样的问题也适用于浏览器。
我有一些异步调用(比如说 setTimeout
或 $.ajax
或 fs.readFile
) 一段时间后,事件循环执行回调,
现在当回调正在执行时,幕后发生了什么? 它是否会恢复调用异步内容时使用的堆栈?
实际上,回调所在的上下文/this 是什么? 它是如何运作的?
编辑:谢谢,我明白了.. 还有一个问题,事件循环如何“记住”回调的范围?
I wonder how the event-loop works in javascript,
I am using node.js but I guess that the same question apply to browsers.
I have some async call (let's say setTimeout
or $.ajax
or fs.readFile
)
and after a while the event-loop executes the callback
now when the callback
is getting executed, what happens behind the scene?
Does the it revive the stack that it used when it invoked the async stuff?
In practice what is the context/this that the callback is living in?
and how does it work?
edit: thanks, I see..
just one more issue, how does the event loop "remembers" the scope of a callback?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
JavaScript 使用函数作用域,作用域规则在所有 JS 环境中都是相同的。正如 Nican 提到的,理解闭包对于了解当前范围内可用的内容非常重要。
基本上,函数“记住”定义它的环境。因此,如果您在回调中使用内联匿名函数,它将可以访问其父函数可用的所有变量以及作为参数传递给它的任何内容。
有关 JavaScript 中的闭包和作用域的一些资源:
Stoyan Stefanov 的书面向对象的 JavaScript 很好地解释了 JavaScript 中的作用域以及 词法作用域有效(参见第 4 章)。我会向任何认真研究 JS 编程的人推荐这本书。
JavaScript uses function scoping, the scoping rules are the same in all JS environments. As Nican mentioned understanding closure is important to knowing what is available in your current scope.
Basically a function "remembers" the environment in which it was defined. So if you use an inline anonymous function for your callback it will have access to all the variables that are available to its parent function and anything that is passed into it as an argument.
A few resources regarding closures and scope in JavaScript:
Stoyan Stefanov's book Object-Oriented JavaScript does a great job of explaining scoping in JavaScript and how the lexical scoping of functions work (see chapter 4). I'd recommend the book to anyone who is serious about JS programming.
有一个很好的工具,名为 Javascript Loupe,由 Philip Roberts 创建,它可以帮助您了解 javascript 的调用堆栈/事件和循环/回调相互交互。在编辑器中编写一些 JavaScript 代码并尝试运行它。
There is a nice tool called Javascript Loupe created by Philip Roberts that will help you understand how javascript's call stack/event and loop/callback intereact with each other.Write some piece of javascript code in the editor and try to run it.