开发者

jQuery constructor and init

开发者 https://www.devze.com 2023-03-14 15:23 出处:网络
If I issue console.dir(jQuery.prototype) I get a beautiful list of the methods and properties that are i开发者_开发知识库n the jQuery object.But constructor and init are in red with a little plus s

If I issue

console.dir(jQuery.prototype)

I get a beautiful list of the methods and properties that are i开发者_开发知识库n 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?


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


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.


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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号