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.

3
  • 1
    Related/dupe: How can jQuery behave like an object and a function? Commented Jan 18, 2012 at 21:18
  • 1
    Don't assume jQuery library design is good. It's not. I recommend you design the framework however you want. Commented Jan 18, 2012 at 21:21
  • The right term is not, anonymous method. You're looking for methods in the pool of prototype, chaining. Commented Jan 18, 2012 at 21:22

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.