I have an IIFE that returns an object. In my app.js file, which I add to a script tag in index.html, I log to the console typeof my IIFE and it is an object. Shouldn't it be a function? Why is typeof returning an object?
Here is my IIFE in app.js:
var UIController = (function() {
var DOMstrings = {
inputType: '.add__type',
description: '.add__description',
value: '.add__value',
addBtn: '.add__btn'
};
return {
getInput: function() {
// return an object containing all values from UI elements
return {
type: document.querySelector(DOMstrings.inputType).value, // will be either income or expense
description: document.querySelector(DOMstrings.description).value, // description of transaction
value: document.querySelector(DOMstrings.value).value // value of transaction
};
},
getDOMStrings: function() {
return DOMstrings;
}
};
})();
console.log(typeof UIController);
IIFE stands for “immediately invoked function expression.” In other words, an expression created by invoking a function . Invoking a function means to call the function and produce a result. The value of an IIFE is the result of calling (invoking) the function, not the function itself.
In your example, the variable UIController
is assigned the result of calling a function. Your function returned an object with two properties. The object is assigned to UIController
. So typeof UIController
produces object
as expected.
**REMEMBER Immediately Invoked FUNCTION EXPRESSION FUNCTION (IIFE) are functions whose variables cannot be accessed outside the function & you cannot call that function explicitly(this will give error) **
*here is a simple code to clear concept of IIFE. this function just prints hey & do not have any return value *
var run=(function(){
console.log("HEY");
})();
run(); //error
console.log(run); HEY
console.log(typeof(run)); undefined
*Below IIFE functions returns the value *
var run=(function(){
return 1;
})();
run(); //error
console.log(run); 5
console.log(typeof(run)); number
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.