6

I'm trying to create a mini jQuery clone that can support method chaining. So far I've came up with this piece of code:

var $ = (function () {

  var elements = [];

  function methodOne() {
    console.log('Method 1');
    return this;
  }

  function methodTwo() {
    console.log('Method 2');
    return this;
  }

  return {
    methodOne: methodOne,
    methodTwo: methodTwo
  };
}());

At page load, the $ variable gets populated with the jQuery clone object returned by the IIFE.

My question is, how can I make the $ object to be called directly as a function while still maintaining the method chaining functionality?

Right now, I can use $.methodOne().methodTwo() but I cant use $('some parameter').methodOne().methodTwo() just like jQuery does.

1
  • I haven't tried but I think you could use the class javascript and extends Jquery! I think that will do it. You know, I'm curious and I will try too. Commented Apr 27, 2017 at 11:03

2 Answers 2

3

var $ = function (param) {

  var elements = [];
  console.log(param);

  function methodOne() {
    console.log('Method 1');
    return this;
  }

  function methodTwo() {
    console.log('Method 2');
    return this;
  }

  return {
    methodOne: methodOne,
    methodTwo: methodTwo
  };
};

$('This is a param').methodOne().methodTwo();

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

Comments

1

Working fiddle. The comments should be more or less self explanatory.

It might look a bit long, but it will let you create new mini jQuery object every time you call it.

var _ = (function () {

    var Magic = function(query){
        if(window === this)
            return new Magic(query);

        // reference to itself
        var that = this;

        //assign pseudo public methods and variables
        that.elements = [];
        that.methodTwo = methodTwo;
        that.methodOne = methodOne;

        //fills inner element array with DOM element 
        _get(query);

        function _get(query){
            var elem = document.getElementById(query);
            that.elements.push(elem);
        }

        function methodOne() {
            console.log('Method 1');
            return that;
        }

        function methodTwo() {
            console.log('Method 2', that.elements);
            return that;
        }

        return this;
    } 

    //returns function, which is assigned to a "_" variable
    return function(query){
        //everytime "_" is called, it will return new instance for object Magic which makes all the work
        return new Magic(query);
    } 

}());

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.