How is jQuery's $ a function and an object?

前端 未结 8 787
名媛妹妹
名媛妹妹 2020-11-29 08:22

I mean object as in {} [object Object]. How does it do $(selector) and $.fn.init at the same time?

Can you give me a simple ex

相关标签:
8条回答
  • 2020-11-29 08:43
    var s = function(){};
    s.test = function(){console.log('inside s');}
    s.test();
    

    is perfectly legal code.

    0 讨论(0)
  • 2020-11-29 08:45

    jQuery or $ is an function(you know $ is an alias of jQuery).

    // Define a local copy of jQuery
    jQuery = function( selector, context ) {
        // The jQuery object is actually just the init constructor 'enhanced'
        return new jQuery.fn.init( selector, context, rootjQuery );
    },
    

    In Javascript, everything is an object even function too. Hence You can directly add properties to function.

       jQuery.find = function () {
       }
    
    0 讨论(0)
  • 2020-11-29 08:53

    It is an object.

    $ holds different functions.

    You can test this yourself by making your own object:

    var $ = {
         select: function(id){return document.getElementById(id);}
    }
    
    function $(id){
          return $.select(id);
    }
    
    0 讨论(0)
  • 2020-11-29 08:55

    This isn't unique to jQuery, but an aspect of javascript. All functions are objects. E.g.:

    var f = function() { alert('yo'); }
    f.foo = "bar";
    
    alert(f.foo); // alerts "bar"
    f();          // alerts "yo"
    
    0 讨论(0)
  • 2020-11-29 08:55

    Javascript is an object oriented language, so functions ARE objects, just fancy ones that you can call.

    foo = function() { console.log("foo") }
    foo.bar = function() { console.log("bar") }
    foo() //=> prints "foo"
    foo.bar() //=> prints "bar"
    
    0 讨论(0)
  • 2020-11-29 08:55

    $ is a function. a method of $ can return any thing.

    For example:

    $ = function() {
         return {
                     foo : function() { return 'baa'; },
                     r1: 1,
                     r2 : 'string'
                }
    };
    
    typeof $ <- function 
    typeof $() <- object
    typeof $().foo <- function 
    typeof $().foo() <- string
    typeof $().r1; <- number 
    typeof $().r2 <- string
    
    0 讨论(0)
提交回复
热议问题