Does JavaScript compile the function every time it is invoked?

为君一笑 提交于 2019-12-30 07:34:57

问题


Say I have this function:

function A() {
  function B() {
    return 1;
  }

  return 1 + B();
}

Does function B gets compiled every time when I call function A?

I remember someones says it won't. But my memory gets rusty, and I cannot find the reference.


回答1:


The JavaScript standard states that a JavaScript execution environment must parse the function and produce early errors refusing to execute any code in the script if they exist (such as missing close quotes, unmatched curly braces etc.). It says nothing about what happens after than.

However, all modern engines will produce native code corresponding to the function prior to executing it. All subsequent invocations will use the code generated earlier. There are times where an engine will regenerate the code by using information it collected by execution or it might inline the code of the function if it can determine that would result in better execution time.




回答2:


JavaScript is an interpreted language, not a compiled one, therefore it never compiles the function.

Edit: Unless your javascript engine optimized by compiling, in which case it depends on which engine it is but don't worry about it because it's not going to recompile it without a reason.




回答3:


If you mean invoked (or called) as opposed to compiled, the answer is yes. B is invoked everytime A is invoked as A calls B.



来源:https://stackoverflow.com/questions/20390912/does-javascript-compile-the-function-every-time-it-is-invoked

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!