Reputation: 8268
The following code prints "true". I can understand why ff.f is equal to undefined, but I don't understand why console.log("Hi") is not executed inside ff.f when checking this value. Isn't f immediately executed upon definition?
var ff = function(){
var f = function(){
console.log("Hi");
}();
};
console.log(ff.f === undefined);
[Edit] I guess a better way to ask this question is "When does this f function inside ff get executed?". I think it's weird that ff.f's value is "undefined" if it doesn't get executed until ff gets executed. Shouldn't it be the function instead?
Upvotes: 3
Views: 3053
Reputation: 160015
No, it is not - it is executed once it is evaluated - which in this case is when the parent function (ff
) is executed.
f
executedAny IIFE will be executed once it is evaluated - any such expressions included inside of other functions will only evaluated once the function it is scoped to (wrapped in) executes:
// Executed when the execution flow reaches this point
// i.e. immediately after the script starts executing
var outer = function() {
console.log("Hello from outer");
}();
var wrapper = function() {
// Executed when the flow reaches this point
// which is only when the function `wrapper`
// is executed - which it isn't, so this never fires.
var inner = function() {
console.log("Hello from inner");
}();
};
ff.f
is not a functionJavaScript is function scoped but JavaScript does not provide any way to access a function's inner scope (at least not, as far as I am aware). So when you try to access ff.f
you are looking for a property named f
on the function ff
- and by default there is no such property. Even if you did:
var ff = function () {
ff.f = function() {
console.log("Hello from f");
}();
};
ff.f
would still be undefined
(because the IIFE does not return anything).
Upvotes: 4