javascript - jQuery 如何如此快速地克隆它的方法?

标签 javascript jquery object prototype sizzle

我试图返回一个类似对象的查询,在我的第一次尝试中,我尝试了 Object.create 方法

var ElementArray = {
    someMethod : myMethod,
    ....
}

var addMethods = function(elements) {
    var obj = Object.create(ElementArray);
    obj[0] = elements;
    return obj;
};

var getId = function( query ) {
    return addMethods( doc.getElementById(query) );
};

(jsperf)

我立即发现这比 jQuery(sizzle) 慢,尤其是在 Firefox 上。 Firefox 的问题可能与跨隔室包装器有关 (see bug here) ,但我还是很不满意。

我也尝试过使用原型(prototype)

var ElementArray = function(){};
ElementArray.prototype.someMethod = someMethod;
....

var addMethods = function(elements) {
    var obj = new ElementArray();
    ....
};

在 Chome 上稍好一些,但在 Firefox 上仍然很慢。

所以我的问题是,jQuery(sizzle) 和其他库是如何做到的 ||返回具有 1-2 个实例属性的对象的最快方法是什么? (其他仅供引用)

最佳答案

So my question is, how does jQuery(sizzle), and other libraries do it

jQuery 使用原型(prototype)。它通过将原型(prototype)别名为 .fn 来隐藏这一事实,但它仍然是原型(prototype)。这是the jQuery function .

jQuery = function( selector, context ) {

    // The jQuery object is actually just the init constructor 'enhanced'
    // Need init if jQuery is called (just allow error to be thrown if not included)
    return new jQuery.fn.init( selector, context );
},

而且,这是 the aliasing :

jQuery.fn = jQuery.prototype

并且,执行the actual jQuery constructor :

init = jQuery.fn.init = function( selector, context, root ) {
    var match, elem;

    // HANDLE: $(""), $(null), $(undefined), $(false)
    if ( !selector ) {
        return this;
    }

    // Method init() accepts an alternate rootjQuery
    // so migrate can support jQuery.sub (gh-2101)
    root = root || rootjQuery;

   .....

还有,迂回assignment of the `.init.prototype' :

// Give the init function the jQuery prototype for later instantiation
init.prototype = jQuery.fn;

关于javascript - jQuery 如何如此快速地克隆它的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33060873/

相关文章:

java - 如何使用 Java 主类中创建的对象将值传递给方法

swift - 在初始化时将对象添加到列表

javascript - SVG 围绕圆圈设置虚线动画

javascript - Selenium Web 驱动程序访问 Jquery 中的 Javascript 全局变量

javascript - 数据表列未对齐

c# - 使用 asp.net 将对象传递到不同的页面

javascript - 在Extjs中提示警告消息框

javascript - JQuery 删除带有指针事件的类 none 不起作用

javascript - 如何将动态创建的对象绑定(bind)到文档就绪事件?

javascript - jQuery 数据表 : Individual column searching not working