1

I have a bunch of functions in my script which resides in a .js file. How can avoid conflicts with the names of my functions within the same page if some other script written by some other guys use the same function names as in my script ?

Is there a way to do this?

1
  • u cannot avoid it completely, but if u wrap in inside a class that will much of sense Commented Apr 9, 2013 at 10:05

2 Answers 2

7

If you don't need access to those functions outside of your script you can wrap the whole script in an immediately invoked function expression:

(function () {
    // Your code here
}());

This introduces a new scope, so any declarations within it are not visible outside of it.

If you do need access outside of that scope, expose your functions as methods of a "namespace":

var YourStuff = (function () {
    // Private functions etc...

    // Expose public methods
    return {
        someMethod: function () {}
    };
}());

By taking this approach you only introduce a single global identifier, reducing the chances of a conflict. You can call the method as follows:

YourStuff.someMethod();
Sign up to request clarification or add additional context in comments.

2 Comments

@alex23 - How can affect the timing of anything? And what do you mean by "overlapping closures"?
@alex23 - Yes, they are, there is no such thing as "private" really in JavaScript. IIFEs execute once they've been evaluated... same as any other function invocation. It has nothing to do with the DOM. If you need to wait for DOM-ready, you can use a DOM-ready even handler within your IIFE.
5

Use namespaces..

var company = {};

company.doSomething = function() {
};

company.project = {};
company.project.submodule = {};
company.project.submodule.doSomething = function() {};

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.