Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery object data structure

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.

like image 336
Andrei Cucea Avatar asked Apr 27 '17 10:04

Andrei Cucea


People also ask

What is a jQuery object?

A jQuery object is created from the array elements in the order they appeared in the array; unlike most other multi-element jQuery operations, the elements are not sorted in DOM order. Elements will be copied from the array as-is and won't be unwrapped if they're already jQuery collections.

Are JavaScript objects data structures?

Objects (hash tables) In JavaScript, an object is a collection of key-value pairs. This data structure is also called map, dictionary or hash-table in other programming languages. We use curly braces to declare the object. Then declare each key followed by a colon, and the corresponding value.

What is $$ in jQuery?

$ is another, which is just an alias to jQuery . $$ is not provided by jQuery. It's provided by other libraries, such as Mootools or Prototype.


1 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();
like image 128
Jurij Jazdanov Avatar answered Oct 15 '22 03:10

Jurij Jazdanov