【问题标题】:How does jQuery clone its methods so quickly?jQuery 是如何快速克隆它的方法的?
【发布时间】:2016-01-08 17:41:00
【问题描述】:

我正在尝试返回类似对象的查询,在我的第一次尝试中,我尝试了 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 个实例属性的对象的最快方法是什么? (其他都可以作为参考)

【问题讨论】:

  • jQuery 使用prototype 作为它的方法。因此,在创建新对象时,除了系统设置原型引用之外,没有其他工作可做。
  • @jfriend00 搜索 sizzles github repo 我没有找到原型方法(我搜索过).prototype ...我错过了什么吗?
  • 在内部,它使用.fn,但别名为.prototype,它实际上不在jQuery上,而是在不同的对象上。
  • 在此处查看 jQuery 函数:github.com/jquery/jquery/blob/master/src/core.js#L18。这是jQuery.init.prototype,请看这里:github.com/jquery/jquery/blob/master/src/core.js#L38

标签: javascript jquery object prototype sizzle


【解决方案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;

【讨论】:

    猜你喜欢
    • 2018-12-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-08
    • 1970-01-01
    相关资源
    最近更新 更多