I'm defining various modules in a Javascript
file:
var module = {/* ... */}
(function(){
console.log('Invoked');
})()
However the IIFE
throws an error:
> TypeError: object is not a function
I tried just copy and pasting the IIFE
code and there is no issue.
Immediately invoked function expressions can be used to avoid variable hoisting from within blocks, protect against polluting the global environment and simultaneously allow public access to methods while retaining privacy for variables defined within the function.
An Immediate-Invoked Function Expression (IIFE) is a function that is executed instantly after it's defined. This pattern has been used to alias global variables, make variables and functions private and to ensure asynchronous code in loops are executed correctly.
The JavaScript exception "is not a function" occurs when there was an attempt to call a value from a function, but the value is not actually a function.
Relations That Are Not Functions. A function is a relation between domain and range such that each value in the domain corresponds to only one value in the range. Relations that are not functions violate this definition. They feature at least one value in the domain that corresponds to two or more values in the range.
The module definition needs a semicolon at the end of the declaration:
var module = {/* ... */}; // <======= Semicolon!
(function(){
console.log('Invoked');
})()
Without it Javascript is trying to call the object:
var module = {/* ... */}(function(){console.log('Invoked');})()
Or shortened:
var module = {/* ... */}()
You'd get the same problem when trying to writing two IIFEs next to each other:
(function(){})()
(function(){})()
This doesn't work because a single function declaration returns undefined
:
TypeError: undefined is not a function
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