Hakan
Hakan

Reputation: 3885

Question about cache in javascript/jquery

I wonder if selector "$cacheA" will be cached on page load in the example below?

// MY JQUERY FUNCTION/PLUGIN
(function( $ ){
$.fn.myFunction = function() {

var $cacheA = this,
$cacheB = $cacheA.children(),
$cacheC = $cacheB.eq(0);
$cacheD = $cacheA.parent();    

$cacheD.click(function(){

$cacheA.toggle();
$cacheB.fadeIn();
$cacheC.slideUp();

});

};
})( jQuery );
// END JQUERY FUNCTION/PLUGIN



$(window).load(function(){

$('#mySelector').myFunction();

});

Would it be any reason to do this:

$(window).load(function(){

var $mySelector = $('#mySelector');

$mySelector.myFunction();

});

Upvotes: 0

Views: 218

Answers (2)

buryat
buryat

Reputation: 384

Firstable, $cacheA and others inside click function will be undefined.

$cacheD.click(function(){

$cacheA.toggle();
$cacheB.fadeIn();
$cacheC.slideUp();

});

Second,

$.fn.myFunction = function() {

var $cacheA = this,
$cacheB = $cacheA.children(),
$cacheC = $cacheB.eq(0);
$cacheD = $cacheA.parent();
}

So, after $('selector').myFunction() how can I use $cacheB, $cacheC and $cacheD? Where they are will store?

Upvotes: 0

Pointy
Pointy

Reputation: 413702

If, inside your "load" handler, you were to do many jQuery operations with "$mySelector", then saving that in a variable would be a good idea. However, in your example, you only use the value once, so it really makes no difference at all.

Upvotes: 2

Related Questions