在javascript中定义另一个函数内的函数 [英] define function within another function in javascript

查看:126
本文介绍了在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();
    }
}

如果以上是正确的, bar()每次调用 foo(a)时重新定义? (担心这里浪费cpu资源)

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

推荐答案

是的,你拥有的是正确的。一些注意事项:

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


  • bar 是在每次调用函数<$ c时创建的$ c> foo ,但是:


    • 在现代浏览器上,这是一个非常快速的过程。 (有些引擎可能只编译代码一次,然后每次使用不同的上下文重用该代码; 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天全站免登陆