76 bytes for faster jQuery

时间:2022-01-03 00:40:39

转载自http://james.padolsey.com/javascript/76-bytes-for-faster-jquery/

作者JAMES PADOLSEY

在我们平时使用JQuery,调用了一个回调函数,我们会根据迭代中this对象的不同来确定上下文,然后在用$(this)构建$对象来使用jQuery对象里的方法。像这样

html

<a><span>link1</span></a>
<a><div>link2</div></a>

js

$("a").click(function(){
console.log($(this).text());
})

每次迭代,都创建一个新的对象,这些jQuery对象似乎是很多余的,尤其是当迭代次数很多的时候。

下面来看一个优化的写法,共用一个jQuery对象。

// 只创建一个jQuery对象
var $obj = $([1]); $("a").click(function(){ // 给出需要操作的this
$obj[0] = this; // 共用先前的jQuery对象中的方法
console.log( $obj.text());
})

这是一种flyweight的概念,共享数据,无论我们有多少次迭代,我们都只创建了一个jQuery对象并使用其.text()。

现在这只是概念,为了更好的运用到实际当中,JAMES PADOLSEY给出了良好的函数

jQuery.single = (function(o){

    var collection = jQuery([1]); // Fill with 1 item, to make sure length === 1

    return function(element) {

        // Give collection the element:
collection[0] = element; // Return the collection:
return collection; }; }());

使用

jQuery('a').click(function(){

    console.log($.single(this).text()); 

});

常常的,在一些编码当中,我们不需要创建jQ对象,但我们要使用jQuery.fn里的函数,且要可以链式使用。这时我就可以使用JAMES PADOLSEY的$.single了。