How jQuery can call an $ object

  • If it $is an object, then how jQuery can call it with a bracket (), for example $('#MYdIV'). This is my first and most important question.

  • I am trying to learn design patterns and implement object creation mechanisms. So I want to create a library that, when the user types in myLibrary({option1:true});, can instantiate the object without using the new.Just keyword like jquery and this is: https://github.com/bendc/animateplus/blob/master/animate.js In this example he does not use the keyword newand this. It simply creates an IIFE animation that returns another function with the same name. I do not know how he can do this. Is the animation attached to a global object?

+4
source share
3 answers

jQueryor $- it's just a function. Consider the following example, which creates an object with similar behavior.
Of course, jQuery has a much more complex and intelligent structure, this is just an example:

var not$ = function(o) {
  var result = document.querySelectorAll(o);
  
  result.customInnerText = function(text) {
      if (text === undefined) {
        return document.querySelector(o).innerText;
      } else {
        document.querySelector(o).innerText = text;
      }     
  };
  result.customClickHandler = function(callback) {
      document.querySelector(o).addEventListener('click', callback);
  };

  return result;
};
not$.customConsoleLog = function(text) {
    console.log(text);
};

not$("a").customClickHandler(function() {
  var exampleText = not$("#title").customInnerText();
  not$("#text").customInnerText(exampleText + "It works!");

  not$.customConsoleLog(not$("p").length);
  not$.customConsoleLog(not$("p")[0]);
});
 
<a href="#">Click me!</a>

<p id="title">Example:</p>
<p id="text">Check!</p>
Run code
+3
source

(1) $ not an object, but a function.

console.log(typeof $);
// function

What can be confusing here - and this is just a hunch - is that you can access properties in a variable $, for example. $.extendor $.fn(used when writing your own jQuery plugins). This is normal because functions can have properties. ECMAScript specifications allow this.

(2) , . , . @Jeff , , new, . . , .

+1

:

  • : string, number, boolean, null, undefined, symbol
  • - , , , Javascript. , , .
  • - , javascript. function()
  • - . , new, new Thing(). - .

, , JQuery , -. , , - $ = function() {...}

- $ , . , , , $.randomNumber = 4 , JQuery .

So, if you want to do something like this, you will want to define your own global variable and set it as a function - just be aware of what has already been done, i.e. do not use $or _or anything else.

+1
source

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


All Articles