I just accidentally discovered this weird thing, and I am wondering if it's a bug, or an expected behavior.
let myfunc = function(a) {
return function localScope(b) {
console.log(a + b + " this")
}
}
(function () {
console.log('test')
})()
The first function returns a function. I never invoke either of them.
Then below, I create a self-invoking function, and what happens is, the self-invoking function is not invoked, instead, it's passed as the a
argument to the above myFunc
parent function, and then somehow the myFunc
is invoked, and for some reason, the returned localScope
function is also invoked, and it consoles out the body of the self-invoking function.
However, this does not happen if I declare the self-invoking function differently by enclosing it with brackets, like this:
(function () {
log('test')
}())
Is this like a bug, or is this an expected behavior? Why does declaring the self-invoking function differently makes a difference?
I am guessing this has to do with the scope object, but I have no idea what's happening here. Why is the self-invoking function passed as an argument, and why and how is the local function inside the parent invoked.