在javascript中嵌套函数内存使用 [英] nested function memory usage in javascript

查看:214
本文介绍了在javascript中嵌套函数内存使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在javascript中理解闭包,但我不知道是如何处理嵌套函数。例如:

I sort of understand closures in javascript, but what I'm not sure about is how it treats nested functions. For example:

var a = function(o) {
    o.someFunction(function(x) {
        // do stuff
    });
}

我知道每次调用function a ,但是闭包是否也包含传递给 someFunction 的匿名函数的新实例?如果我做了ff,它会更好:

I know a new closure is created everytime I call function a, but does that closure also include a new instance of the anonymous function passed to someFunction? Would it better if I did the ff instead:

var b = function(x) { /* do stuff */ }
var a = function(o) {
    o.someFunction(b);
}


推荐答案

a被调用的时间,定义一个匿名函数并传递给 someFunction()。这比第二个例子中的代码更昂贵,这是更有效的方法,因为函数(现在称为b)只定义一次。

In your first example, every time that a is called, an anonymous function is defined and passed to someFunction(). This is more expensive than what you've got in the second example, which is the more efficient method, since the function (now called b) is only being defined once.

我问了一个类似的问题几个月前回来:它可能会帮助你以及。 使用匿名功能会影响效果吗?

I asked a question similar to this a few months back: it might help you as well. Does use of anonymous functions affect performance?

这篇关于在javascript中嵌套函数内存使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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