简体   繁体   中英

Immediately invoked function expression throws “object is not a function”

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.

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

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM