Long ago I've read a lot about javascript coding conventions, and one of the things I wanted to decide was the better way of declaring functions. I finally somehow stuck with the
var func_name = function(){};
version, because it seemed more useful in certain scenarios, but I wasn't really able to find things that wouldn't work the same way between them until now.
I was writing a function that should've returned a new function to be used in a setTimeout command, but I couldn't get it to work properly, and after I reduced the whole thing to this test code:
var test = new function(x) {
return function() {
if (x % 2 == 1) {
console.log('a');
}
else {
console.log('b');
}
x++;
};
};
I happened to try if writing it in the
function func_name(){}
style would help (because I really couldn't see the problem with my code), and interestingly enough this code
function test(x) {
return function() {
if (x % 2 == 1) {
console.log('a');
}
else {
console.log('b');
}
x++;
};
}
seems to be working perfectly. A weird thing to discover was that after playing a bit around in the console I realized that the first one effectively becomes the function it should generate.
I tested it in Chrome and Firefox too, and I also tried using it this way
var test = new function(x) {
var result = function() {
if (x % 2 == 1) {
console.log('a');
}
else {
console.log('b');
}
x++;
};
return result;
};
but I wasn't able to make it work.
I would be interested in any explanation to this phenomenon and also it fascinates me if there is a way to make this type of function declaration capable of producing functions.
Thanks in advance!
Edit: I don't know how, but somehow that new keyword got there by mistake :D (and even into the third version by that stupid copy-paste laziness of mine.....)
I'm still interested in knowing why the function becomes what it should create though!
new, just usevar test = function() ...