I'm coming from C#/PHP and trying to get my head around Javascript's idea that functions are variables/objects and have quasi constructors, etc.
Can anyone explain why the following code functions as it does, namely:
- Why isn't "2" displayed when instantiating the variable/function
test
? - Why isn't "1" displayed when executing the variable/function
test
?
code:
var setup = function () {
console.log(1);
return function() {
console.log(2);
};
};
var test = setup(); // 1
test(); // 2
test(); // 2
test(); // 2
added:
Thanks @thejh @Justin so the function is returning a completely different function that has nothing to do with the first (I was thinking of the second function as a kind of constructor of the first), if I comment it out, it's clearer:
$(document).ready(function() {
var setup = function () {
console.log(1);
// return function() {
// console.log(2);
// };
};
var test = setup(); // 1
test(); // "test is not a function"
test(); // "test is not a function"
test(); // "test is not a function"
});