在JavaScript中的另一个函数中定义一个函数 [英] Define a function within another function in JavaScript

查看:65
本文介绍了在JavaScript中的另一个函数中定义一个函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

function foo(a) {
    if (/* Some condition */) {
        // perform task 1
        // perform task 3
    }
    else {
        // perform task 2
        // perform task 3
    }
}

我有一个函数,其结构与上述类似.我想将任务3 抽象为一个函数bar(),但是我希望将此函数的访问限制为仅在foo(a)的范围内.

I have a function whose structure is similar to the above. I want to abstract task 3 into a function, bar(), but I wish to limit the access of this function to only within the scope of foo(a).

要实现我想要的,更改为以下内容是否正确?

To achieve what I want, is it right to change to the following?

function foo(a) {
    function bar() {
        // Perform task 3
    }

    if (/* Some condition */) {
        // Perform task 1
        bar();
    }
    else {
        // Perform task 2
        bar();
    }
}

如果上述正确,那么每次调用foo(a)时是否重新定义bar()? (我担心这里会浪费CPU资源.)

If the above is correct, does bar() get redefined every time foo(a) gets called? (I am worrying about waste of CPU resource here.)

推荐答案

是的,您所拥有的是正确的.一些注意事项:

Yes, what you have there is right. Some notes:

    在每次调用函数foo时都会创建
  • bar,但是:
    • 在现代浏览器上,这是一个非常快速的过程. (有些引擎可能只为它编译一次 code ,然后每次在不同的上下文中重复使用该代码; Google的V8引擎(在Chrome和其他地方)在大多数情况下都可以做到这一点.)
    • 并且根据bar的作用,某些引擎可能会确定可以内联"它,从而完全消除了函数调用. V8做到了这一点,我敢肯定它不是唯一的引擎.自然,他们只有在不改变代码行为的情况下才能这样做.
    • bar is created on every call to the function foo, but:
      • On modern browsers this is a very fast process. (Some engines may well only compile the code for it once, and then reuse that code with a different context each time; Google's V8 engine [in Chrome and elsewhere] does that in most cases.)
      • And depending on what bar does, some engines may determine that they can "inline" it, eliminating the function call entirely. V8 does this, and I'm sure it's not the only engine that does. Naturally they can only do this if it doesn't change the behavior of the code.

      这篇关于在JavaScript中的另一个函数中定义一个函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆