Newcoma
Newcoma

Reputation: 809

jquery caching elements once when run multiple times

I am curious about if cachevar() will cache the el element once or everytime I run it?

function cachevar() {
    var el = $('.element')
    el.toggleClass('open') 
}
cachevar();

Upvotes: 0

Views: 66

Answers (2)

Alessandro Vendruscolo
Alessandro Vendruscolo

Reputation: 14877

It will allocate a new variable every time you call it.

So it won't "cache" anything.

If you need to have a function that you plan to call many times and want to cache the elements it uses, you need to move those in a closure:

var el = $('.element');
function cachevar() {
    el.toggleClass('open') 
}
cachevar();
cachevar();

By doing so, cachevar will access to the same el object.

You can't cache objects without having them in a closure. If you don't want to have el clobbering your current scope, you can wrap that in a-so-called IIFE (Immediately Invoked Function Expression) so that it creates a new scope:

var cachevar = (function () {
    var el = $('.element');
    return function () {
        el.toggleClass('open') 
    }
}());
// el is undefined here
cachevar();
cachevar();

Upvotes: 2

Jai
Jai

Reputation: 74738

This will cache it everytime you call your function:

function cachevar() {
   var el = $('.element')
   el.toggleClass('open') 
}
cachevar();

so if you declare a global function then once you call your function then el will be cached to use anywhere then:

var el='';
function cachevar() {
   el = $('.element')
   el.toggleClass('open') 
}
cachevar();

alert(el); //<---here el is '$(".element")'

Upvotes: 0

Related Questions