jQuery构造函数和init

jQuery constructor and init

本文关键字:init 构造函数 jQuery      更新时间:2023-09-26

如果我发布

console.dir(jQuery.prototype)

我得到了jQuery对象中方法和属性的漂亮列表。但是constructor和init是红色的,旁边有一个加号。

Q: 构造函数和init与其他函数有何不同?

Firebug检查函数是否看起来像class函数(obj.prototype至少包含1个属性),并将其显示为具有可扩展属性的class。

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;
}

你可以通过在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]));
}

输出

0: true
1: true
2: false
3: false

我想这是因为构造函数和init不仅仅是"纯"函数。这意味着它们有额外的属性(例如init有自己的原型),这就是它们可扩展的原因。为了进一步说明这一点:

// 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;

换句话说:函数就是一个Object,这意味着你可以附加任何你想要的属性。

这表明这些函数有为其定义/设置的附加属性/方法。