Ben Tinsley Ben Tinsley - 1 year ago 43
Javascript Question

Why does jQuery store an element as a function?

I am calling a div with an ID of car like this:

var car = $('#car');

When I log it, it comes back like this in the console:

[div#car, context: document, selector: "#car", jquery: "1.9.0", constructor: function, init: function…]

Is the "constructor: function" part of the log telling me that it has been stored as a function, and if so why and how to get it to store as an object?

Answer Source

jQuery creates instances of functions when it accepts an argument. In this case, you sent in a selector which was the id of an element. Upon receiving this selector, jquery uses the new keyword on the "internal" jquery function. The result is a function object. Every time you use $ or jQuery you are asking it for a jquery object which is a result of new being issued to the jQuery function. This object has many things attached to it, including the element array matching the selector, and jQuery's prototype which allows for you to access the API.

So, just to clarify. It is an object. It was constructed from a function.


Here is some sample code to help you see how this can happen.

First, this demo is a simple jquery object:


<div id="car"></div>


var car = $("#car");

Second, this is an example that I wrote


<div id="car"></div>


var $ = (function(){
    var $ = function(sel){
        if( !(this instanceof $) ){
            return new $(sel);
        this.selector = sel;
        this.element = document.getElementById(sel);
        this.constructor = $;
        this.init = function(){ /*init*/ };

    return $;

var car = $("car");

You will notice that they both log almost the exact same thing. There is no magic in the $, it is just a string, much like Y is or jQuery, or HelloWorld.