Create Javascript Library

7

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

I know that there are already a lot of good libraries out there (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 as well.

Thank you very much.

    
asked by anonymous 17.08.2015 / 19:07

2 answers

4

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

See 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
    
17.08.2015 / 19:17
4

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

Basically there are two approaches. Create functions that accept all data as arguments, or extend the prototype of DOM elements or JavaScript types.

jQuery covered by the first option, MooTools for example by the second.

In any case, it is important to note that there may be clashes with other libraries and therefore plan well for which names to use.

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

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

And then flames 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 be:

var strLimpa = stringSuja.limpar();

I mentioned 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 add-ons. That way you can use just what you need and keep code and files light.

    
26.08.2015 / 22:38