使用命名函数进行回调 [英] Using named functions for callbacks
问题描述
我在使用匿名函数对javascript进行性能分析时遇到了一个主要问题,我总是有很多匿名函数-其中大多数是回调函数-这使我很难分析探查器的结果.
I have a major problem with profiling in javascript with anonymous functions, I have always many anonymous functions - most of them are callbacks - and It makes analyzing results of profiler very hard for me.
最后,我决定使用命名函数进行回调,如下所示:
Finally I decided to use named functions for callbacks, like this:
var f = function(callback) {
// Do something ...
callback();
}
f(function named_function() {
console.log('Sample callback function!');
});
我想知道在对代码进行此更改后是否会有任何问题?这种类型的函数定义和传递会在任何地方保留名称(named_function)吗?
I want to know that will I have any problems after making this change in my codes? And will this type of function definition and passing reserve the name (named_function) anywhere?
推荐答案
该名称仅在命名函数表达式的范围内可用.
The name will only be available inside the scope of the named function expression.
但是在IE 8及更低版本中存在问题.它会泄漏到外部范围,并实际上会创建一个不同的函数对象,因此如果出现问题,则应将其无效.
But there is a problem in IE 8 and lower. It will leak out to the outer scope, and will actually create a different function object, so you should nullify it if that's a problem.
f(function named_function() {
console.log('Sample callback function!');
});
var named_function = null;
有关更多信息,请参见本文:已解密的命名函数表达式
See this article for more information: Named function expressions demystified
或者您可以像这样创建它来解决IE问题.
Or you could create it like this to solve the IE issue.
f(function() {
return function named_function() {
console.log('Sample callback function!');
};
}());
但这有点丑陋.
这篇关于使用命名函数进行回调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!