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:
test?test?code:
var setup = function () {
console.log(1);
return function() {
console.log(2);
};
};
var test = setup(); // 1
test(); // 2
test(); // 2
test(); // 2
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"
});
You're only calling setup() the first time. Once it is called, the new function it returns is assigned to test. From there on, you're calling that new function:
// calls setup which logs 1 and returns a new function.
// setup also returns a new function and assigns that new function to test.
var test = setup();
// test now is the equivalent of var test = function(){ console.log(2); };
// call the new function that setup returned which logs 2
test();
// and again
test();
// and again
test();
Because you're returning a different function from what gets called when creating it (the one in the return, one you're not calling on the first line)...that's what gets executed on the other calls. For example this would give you 1 then 2:
var test = setup()(); // 1, 2
You can test it here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With