Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery constructor and init

If I issue

console.dir(jQuery.prototype)

I get a beautiful list of the methods and properties that are in the jQuery object. But constructor and init are in red with a little plus sign next to them.

Q: What makes constructor and init different than the other functions?

like image 451
Phillip Senn Avatar asked Jun 22 '11 22:06

Phillip Senn


3 Answers

Firebug checks if a function looks like a Class function (obj.prototype contains atleast 1 property), and shows it as a Class with expandable properties.

http://code.google.com/p/fbug/source/browse/branches/firebug1.8/content/firebug/dom/domPanel.js#531

 if (isClassFunction(val))
    this.addMember(object, "userClass", userClasses, name, val, level, 0, context);

http://code.google.com/p/fbug/source/browse/branches/firebug1.8/content/firebug/dom/domPanel.js#1960

function isClassFunction(fn)
{
    try
    {
        for (var name in fn.prototype)
            return true;
    } catch (exc) {}
    return false;
}

You can test it out by running this in Firebug

function isClassFunction(fn)
{
    try
    {
        for (var name in fn.prototype)
            return true;
    } catch (exc) {}
    return false;
}
test = [jQuery.prototype.init, jQuery.prototype.constructor, jQuery.prototype.each, jQuery.prototype.get];
for(var i = 0; i < test.length; i++) {
    console.log("" + i + ": " + isClassFunction(test[i]));
}

Output

0: true
1: true
2: false
3: false
like image 167
Dogbert Avatar answered Sep 24 '22 17:09

Dogbert


I guess it's because constructor and init are not just "pure" functions. This means they have additional properties (e.g. init has its own prototype), and that's why they are expandable. To illustrate this a bit further:

// size is defined as something like this
jQuery.prototype.size = function() {
    // do stuff
};
// init is defined as a function too, but with additional properties
jQuery.prototype.init = function() {
    // do other stuff
};
jQuery.prototype.init.functionIsAnObject = true;

In other words: A function is an Object, this means you can attach any properties you want.

like image 25
Manuel Leuenberger Avatar answered Sep 26 '22 17:09

Manuel Leuenberger


It shows that these functions have additional properties/methods defined for / set on them.

like image 38
c-smile Avatar answered Sep 22 '22 17:09

c-smile