Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create selector like jQuery with additional functions?

Tags:

javascript

I am trying to understand how to work jQuery and other libraries. I would like to know how to create a selector with this format:

$("#selector").get(); 

By the moment, I am trying the next, but i don't know how to run internal functions (get(), set()):

var $ = (function() {

    var jQuery = {
        get: function() {
            console.log("get() function!!");
            return this;
        },
        set: function() {
            console.log("set() function!!");
            return this;
        }
    };

    return function(el) {
        return document.querySelector(el);
    }       
})();

I have read something about modular pattern design in JavaScript, but I don't understand all.

like image 811
Fabián Rodríguez Avatar asked Mar 07 '26 13:03

Fabián Rodríguez


1 Answers

The way to make chainable functions, is to first and foremost create instances with the new keyword.

This can be done "automatically" by making sure the this value of the called function is an instance of itself, if not explicitly call it with new.

Then it's just a matter of returning the instance and using prototyped methods.

var $ = function(selector) {
  if (! (this instanceof $) ) {
    return new $(selector);
  }
  this.el = document.querySelectorAll(selector);
  return this;
}

$.prototype.css = function(prop, val) {
  this.el.forEach(function(element) {
    element.style[prop] = val;
  });

  return this;
}

$('#test').css('color', 'red').css('font-size', '30px')
<div id="test">test</div>
like image 164
adeneo Avatar answered Mar 09 '26 02:03

adeneo