Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
548 views
Welcome To Ask or Share your Answers For Others

1 Answer

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...