user523285
user523285

Reputation:

Creating a javascript library closure

I've been developing a JavaScript library similar to Underscore.js and Jquery in the past few days. In both of those libraries they use an object which can accept parameters but can also have methods called on it: $("param").method(); or _("param").method();

I've been reading through the source code on both of these libraries trying to understand how they are implementing such a thing but have been unable to figure it out. I do not know the name of this type of closure so I've been unable to search for it.

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

Upvotes: 3

Views: 2043

Answers (3)

Boopathi Rajaa
Boopathi Rajaa

Reputation: 4729

var lib = (function (param) {

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

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

   return func;
})();

You could use

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

Defining

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

allows you to use

lib("foo").some();

Upvotes: 4

fdreger
fdreger

Reputation: 12495

Don't do anything special, just make a function and add attributes (some of which can be functions):

function a(){
   alert(1);
}

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

Now you can do both:

a()

or:

a.b()

Upvotes: 0

Guffa
Guffa

Reputation: 700382

You just make a function that returns an object that has methods. Example:

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

test("Hello world").show();

Upvotes: 3

Related Questions