简体   繁体   中英

Javascript Module Export call all functions

Is there a way to call all the functions of a module instead of just choosing each one?

For example:

bettermovies.js

 module.exports={ printAvatar: function(){ console.log("Avatar"); }, printLord: function(){ console.log("Lord of the Rings"); }, printGod: function(){ console.log("God Of War"); }, favMovie: "Return of the King" } 

betterindex.js:

 var movies=require('./bettermovies'); movies.printAvatar(); movies.printLord(); console.log(movies.favMovie); 

The reason I ask is because what if I had a hundred movie functions in .js, it'd be real tedious to do it all manually instead of having a function to call all the functions. This actually leads me to another question, say you had 100 of these print"movie" function and you wanted to print all of them except for 3 of them, how would you do that then?

Thanks!

You can iterate through the movies object after the require. Something like that should work:

for (var prop in movies) {
    // Verifies if the property is a function. If it is, the function is called
    if (movies[prop] instanceof Function) {
        movies[prop]();
    } else {
        console.log(movies[prop]);
    }
}

I created a jsfidde . Following code might be solve your problem. The code iterates object and if variable is function, it is called.

var a = {
    printAvatar: function(){
        console.log("Avatar");
        $("body").append("Avatar <br/>");
    },

    printLord: function(){
        console.log("Lord of the Rings");
        $("body").append("Lord of the Rings <br/>");
    },

    printGod: function(){
        console.log("God Of War");
        $("body").append("God Of War <br/>");
    },
    favMovie: "Return of the King"
}

for(x in a){
    if(typeof a[x] == "function"){ // Only if function.
        a[x]();
    }
}

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