Javascript function, such as ie objects "$", can be used as a function, for example. $ () as well as the $ object

Questions in the title. I always wondered and couldn't find out from jQuery source. How it's done.

Repeat. In jQuery: how "$" becomes a function, such as "$ ()", as well as an object of "$."

I can create it one way or the other, for example ...

var $ = function(){ return {each:function(){console.log("Word")}} } // $.each(); FAIL! $().each(); // Word var $ = { each:function(){console.log("Word")} } $.each(); // Word //$().each(); FAIL! 
+4
source share
2 answers

Start with the main function:

 var $ = function(expr) { return $.select(expr); } 

Then add additional functionality:

 $.select = function(expr) { console.log("selecting " + expr); return $; // TODO: perform selection }; $.each = function() { console.log("Called $.each()"); }; 

You can see how this template is used in jQuery by looking at the source :

 var jQuery = function( selector, context ) { // The jQuery object is actually just the init constructor 'enhanced' return new jQuery.fn.init( selector, context ); } jQuery.fn = jQuery.prototype = { init: function( selector, context ) { var match, elem, ret, doc; // Handle $(""), $(null), or $(undefined) if ( !selector ) { return this; } // contents of init() here } } 
+9
source

in javascript, a function is an object. You can create a function with properties, other functions (methods). just write it in javascript and look at myfunc type

 var myfunc = function() { //do stuff } 

when you look at the myfunc type in Firebug, you will see that myfunc is an object.

+2
source

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


All Articles