0

Hi I am building a small simple JS framework for University. I am having issues with doing something like jQuery.

Currently I can call methods by $.method() but struggling on how they do the $().method() as I have looked at the source and can't seem to work out how they actually achieved it. As every time I try to adapt mine to look like theirs it does not work.

So what is the best way to achieve this.

Sam_Benne
  • 595
  • 5
  • 18
  • 1
    Related/dupe: [How can jQuery behave like an object and a function?](http://stackoverflow.com/questions/8734115/how-can-jquery-behave-like-an-object-and-a-function) – Rob W Jan 18 '12 at 21:18
  • 1
    Don't assume jQuery library design is good. [It's not](https://gist.github.com/1417030). I recommend you design the framework however you want. – Raynos Jan 18 '12 at 21:21
  • The right term is not, *anonymous method*. You're looking for methods in the pool of prototype, chaining. – Rob W Jan 18 '12 at 21:22

2 Answers2

2
function $() {
    return Object.create(Proto);
}

$.method = function method() { ... };
Proto.method = function method() { ... };

$.method();
$().method();

So you have a function with properties that are methods and your function returns an object which has methods.

Also another pro tip, $ is a poor variable name, use something more meaningful.

cspolton
  • 4,495
  • 4
  • 26
  • 34
Raynos
  • 166,823
  • 56
  • 351
  • 396
1

Every chainable function call works that way because every function call returns the jQuery object.

For instance,

var $=function(){ return $; }; 
$.foo = function(){return "foo"};

$().foo() //Outputs "foo"
Incognito
  • 20,537
  • 15
  • 80
  • 120