Creating a JavaScript library close

In the past few days, I have been developing a JavaScript library similar to Underscore.js and JQuery. In both libraries, they use an object that can take parameters, but can also have methods called on it: $ ("param"). Method (); or _ ("param"). method ();

I read the source code in both of these libraries, trying to figure out how they implement such a thing, but couldn't figure it out. I do not know the name of this type of closure, so I could not find it.

Any help would be appreciated, I'm just trying to figure out how I can implement an object of this type in my library.

+3
source share
3 answers

You simply create a function that returns an object with methods. Example:

function test(demo) {
  return {
    show: function() { alert(demo); }
  };
}

test("Hello world").show();
+3
var lib = (function (param) {

   var func = function () {
     /// your code

     return {
         animate : function () {
          // do the animation
          return this;
     }
   }

   return func;
})();

lib(function(){}).something();
lib("selector").something().something().something();
lib(DOMElement).something().something().something();

lib.prototype={
some: function() {}
};

lib("foo").some();
+4

Do nothing special, just create a function and add attributes (some of which may be functions):

function a(){
   alert(1);
}

a.b = function(){
   alert(2);
}

Now you can do both:

a()

or

a.b()
0
source

All Articles