How to define a function like jQuery $?

JQuery works with $ as a function, I wanted to know how I can make my own function?

How to make a contractor function in JavaScript? For example, I do this:

window.test = (function () {        
    var test = {
        get: function (selector) {

        }   
    };

    return test;
}());

(for example) I want to select a canvas element when I call test()

+4
source share
2 answers

I think you need this solid object.

var myQuery = function (str) {       
  this.str=str;
  this.concate = function(str){
     this.str= this.str+" "+str;
     return this;
  };
  this.to_string = function(){
     return this.str;
  };
  return this;
};
window['$']=myQuery;

alert($('hello').concate(' $').concate('!!').to_string());
alert(myQuery('hello').concate('myQuery').concate('!!').to_string());
Run code

Another scenario: Declared myQuery reference to $ directly;

var myQuery = (function (str) {       
  if(typeof window['$'] ==="undefined")
  {
  	window['$']=this;
  }
  this.str=str || '';
  this.concate = function(str){
     this.str= this.str+" "+str;
     return this;
  };
  this.to_string = function(){
     return this.str;
  };
  return this;
})();

alert($.concate("From $").to_string());
Run code
+4
source

The correct answer, but I think I understand what you need, and perhaps this answer will also help you:

window["$"] = function (selector) {       
  this.s=selector;
  this.changeColor = function(color){
      document.getElementById(this.s).style.background = color;
     return this;
  };
  return this;
};
<div id="elementId">
  Change my background.  
</div>

<a onClick="$('elementId').changeColor('red');" href="#">Red</a>
<a onClick="$('elementId').changeColor('blue');" href="#">Blue</a>
<a onClick="$('elementId').changeColor('green');" href="#">Green</a>
Run code
+2
source

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


All Articles