user3395757
user3395757

Reputation:

What is the best way to organize the functions in different JS files?

I have a JS file called common.js in which I have implemented some general functions that I would need many times in the whole project.

Sometimes the functions name in common.js are same as other JS file that I might include on a page that would create a conflict and the latest definition will be used which is depends on the order of inclusion of file.

I assume that the way I am handling things is wrong; would like to know how should I handle this kind of situation to have a better readability and flow of code.

Upvotes: 2

Views: 87

Answers (1)

Drew Dahlman
Drew Dahlman

Reputation: 4972

You should namespace them, maybe like Utils or something, you will need to refactor but it is best practice to have things namespaced.

you could easily do something like this -

https://jsfiddle.net/2rjv6qqu/

var utils = {
    foo: function () {
        alert("utils foo");
        this.bar();
    },
    bar: function () {
        alert("utils bar");
    }
}

var another = {
    foo: function () {
        alert("Another foo");
        this.bar();
    },
    bar: function () {
        alert("Another bar");
    }
}

utils.foo();
another.foo();

This is a super basic example of namespacing.

Upvotes: 4

Related Questions