Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Share a JavaScript library's namespace or use your own?

It is fairly well known in JavaScript that declaring variables within the global scope is a bad thing. So code I tend to work on contains namespaced JavaScript.

There seems to be two different approaches taken to this -

  1. Adding your application specific functions to the libraries' namespace e.g. $.myCarouselfunction
  2. Creating your own namespace e.g. MyApplication.myCarouselFunction

I wanted to know whether or not there is a better solution or if they tend to meet somewhere close in terms of pros and cons.

The reason for me personally deciding not to go with the library so far is for Seperation / Isolation / Lack of conflict with library code and potential plugins that are likely to share that namespace. Is there more to this that I'm not considering?

like image 535
Dr. Frankenstein Avatar asked Jun 13 '10 23:06

Dr. Frankenstein


People also ask

Why do we use namespace in JavaScript?

Namespace refers to the programming paradigm of providing scope to the identifiers (names of types, functions, variables, etc) to prevent collisions between them. For instance, the same variable name might be required in a program in different contexts.

Which JavaScript library should I use?

js is an excellent JavaScript library to use. Chart. js is a flexible and simple library for designers and developers who can add beautiful charts and graphs to their projects in no time. It is open-source and has an MIT license.

Why would you use a JavaScript library?

Some client-side JavaScript libraries help abstract away quirks of the web platform. A library can also serve as a learning tool. For example, if you're unfamiliar with animation easing functions, the source code of a library can teach you how such easings work.

Where do I put JavaScript library?

Installing the library. Once you have the . js file, you need to put it in the same place as the rest of your project. For simplicity's sake, put it in the same folder that your sketch.


2 Answers

I think the most important thing in choosing this sort of thing is semantics.

Does your function/class extend or depend on a library-specific feature? Put it in the library namespace.

Is your function/class library-independent? In this case, it is better to put it in a custom namespace. This makes it possible to reuse your code outside the the library you originally used it with.

like image 114
Jani Hartikainen Avatar answered Sep 27 '22 23:09

Jani Hartikainen


Personally I like this sort of approach:

(function(namespace) {

function myPrivateFunction(){};

namespace.myPublicFunction = function(){};

})($); // passing the $ namespace, but if it clutters, 
       // we can change it to something else
like image 41
Luca Matteis Avatar answered Sep 27 '22 22:09

Luca Matteis