Using the named functions for callbacks

I have a big problem with profiling in javascript with anonymous functions, I always have a lot of anonymous functions - most of them are callbacks - and it very much analyzes the results of profiling.

Finally, I decided to use named functions for callbacks, for example:

var f = function(callback) {
    // Do something ...
    callback();
}

f(function named_function() {
    console.log('Sample callback function!');
});

I want to know that I will have problems after making changes to my codes? And will this type of function definition and transmission reserve the name (named_function) anywhere?

+5
source share
5 answers

The name will only be available inside the function namespace.

IE 8 . , , .

f(function named_function() {
    console.log('Sample callback function!');
});
var named_function = null;

. : ,

, IE.

f(function() {
    return function named_function() {
        console.log('Sample callback function!');
    };
}());

.

+8

.

,

var foo = function foo(){};
+1

, .

.

var f = function(callback) {
    // Do something ...
    callback();
}

f(function named_function() {
    console.log(named_function); // Logs the function
    console.log('Sample callback function!');
});

console.log(named_function);​ // Error: named_function is undefined
0

, . , . , :

(function named_callback() { console.log("Callback 1"); })();
(function named_callback() { console.log("Callback 2"); })();​
0
source

Actually, you still create an anonymous function expression and assign it to a local variable with scope f. Go for

function f( callback ) {
    callback();
}

f( named_function );

function named_function() {
    console.log('Sample callback function!');
}

Thus, you even avoid memory leak of the named function name in <= IE8, plus, since you no longer create a function expression, but a function declaration *, you can even access the finside of the body.

0
source

All Articles