jQuery如何快速克隆其方法?

时间:2015-10-11 02:10:42

标签: 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)有关,但我仍然非常不满意。

我也尝试使用原型

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

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

在Chome上稍微好一点,但在firefox上仍然很慢。

所以我的问题是,jQuery(sizzle)和其他库如何做到这一点什么是返回具有1-2个实例属性的对象的最快方法? (其他一切都可以作为参考)

1 个答案:

答案 0 :(得分:1)

  

所以我的问题是,jQuery(sizzle)和其他库如何做到这一点

jQuery使用原型。它通过将原型别名化为.fn来隐藏这一事实,但它仍然是原型。这是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;