nested function memory usage in javascript

隐身守侯 提交于 2019-12-14 01:44:54

问题


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
    });
}

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);
}

回答1:


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?



来源:https://stackoverflow.com/questions/637552/nested-function-memory-usage-in-javascript

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