Create Javascript Library

Asked

Viewed 1,596 times

8

I would like to know how to create my own javascript library, ie, create functions that can be reused in various projects and with easy customization.

I know that there are already several libraries out there very good (Jquery for example), but this question is only for my learning and growth as a professional, I believe it will be of great help to others too.

Thank you very much.

2 answers

5

Anyone can create a library, and this is very useful in small projects where you need specific methods and so often it is better to organize the code.

Basically there are two approaches. Create functions that accept all data as arguments, or extending the prototype of elements of the DOM or guys javascript.

jQuery approached by the first option, Mootools for example by the second.

In any case it is important to bear in mind that there may be clashes with other libraries and so plan well what names are used.

If you want an API around an object, yours, you could do it like this:

var MetodosMeus = {
    foo: function(str){
        // fazer algo
    },
    bar: function(arr){
        // fazer algo
    }
};

And then you call for example:

var strLimpa = MetodosMeus.limpar(stringSuja);

Doing the same via extension in the prototype would be

String.prototype.limpar = function(){
    // fazer algo
};

and to use would:

var strLimpa = stringSuja.limpar();

I mentioned above Mootools which is also a modular library, which jQuery does not allow in the same way. So if your library gets big, it’s best to have modules that can work as additions. That way you can only use what you need and keep the code and files light.

5

I think a good start would be studying the pattern Module.

Take an example:

var Counter = (function(){
  var count = 0;

  return {
      count: function() {
        return count;
      }

    , increment: function() {
        return count += 1;
      }
  };
})()

Counter.increment(); // Imprime: 1
Counter.increment(); // Imprime: 2
Counter.increment(); // Imprime: 3
  • Thank you very much, I’m going to study right now.

  • Just tell me one thing, in case I want to do a function whose variables of the method to be executed have a default value, but which can be changed if I want to do it, I would do it with parameters in the same immediate function? An example of what I’m talking about is Jquery’s fadein(), which has a default value for duration, but can be customized.

  • @Lucas, I think this is another question. But jQuery treats this internally, within the function

  • Do not mark the answer as solved yet. I believe better answers will come up

  • Okay, I’ll wait

Browser other questions tagged

You are not signed in. Login or sign up in order to post.