JQuery object data structure

I am trying to create a mini jQuery clone that can support a chain of methods. So far I have come 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
  };
}());

When the page loads, the variable is $populated with the jQuery cloning object returned by IIFE.

My question is: how can I make an object $be called directly as a function, while preserving the functionality of the method chain?

Currently I can use $.methodOne().methodTwo(), but I can not use $('some parameter').methodOne().methodTwo(), as jQuery does.

+6
source share
2 answers

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();
Run codeHide result
+3
source

. .

, mini jQuery , .

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);
    } 

}());
+1

Source: https://habr.com/ru/post/1016819/


All Articles