我试图返回一个类似对象的查询,在我的第一次尝试中,我尝试了 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) );
};
我立即发现这比 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/