While I was at home playing some Javascriptz and, I faced something...
I made a simple function that returns each char from a string or each position value from an array:
function each (haystack, callback) {
var each;
for (each in haystack){
if (callback && typeof callback == "function") {
callback (haystack[each]);
}
}
}
How to use:
each ("StackOverflow", function (c) {
console.log(c);
});
I was wondering if there was a way I could turn /\ that, into this:
each ("StackOverflow", c) {
console.log(c);
}
Or at least something like this, anything that you don't need to rewrite the word function
for the callback.
I tried this, but with no success:
each ("StackOverflow",
"console.log(c)" // turn the callback function into a string
// but where was `c` defined here? do.not.ask.me.
);
And the each()
was:
function each (haystack, callback) {
var each;
for (each in haystack){
// call it in a setTimeout() crazy? yeah, didn't work...
setTimeout(callback, 0);
//and also tried this, no success...
var b = new Function ("haystack[each]", cb);
b ();
}
}
My conclusion here is, unfortunately we can't have a callback function without declaring an anonymous function.
Is there a way I can make a callback function without using the work function
?