The forums ran from 2008-2020 and are now closed and viewable here as an archive.

Home Forums JavaScript Cache Your jQuery objects In a jQuery object itself

  • This topic is empty.
Viewing 3 posts - 1 through 3 (of 3 total)
  • Author
  • #39197

    I just had an interesting thought that I’d never seen published anywhere yet about jQuery. It’s real simple, nothing new, but I’d never thought about it before.

    Normally, I’d do something like this:

    var menu    = $('.main-menu'),
    items = menu.find('li'),
    anchors = menu.find('a');

    But down the line in my code, using items loses its connection with menu. I mean sure, I could have used variables like ‘menuItems’ and ‘menuAnchors’, but why do that when you could just do:

    var menu = $('.main-menu');

    menu.items = menu.find('li');
    menu.anchors = menu.find('a');

    // Later
    menu.anchors.on('click', function() {}); // etc...

    Of course you’re limited to using variable names that aren’t already in use by javascript and jQuery, but its convenience is nice to logically group objects together like that.

    I mean, you could do the same with creating an empty object first, then storing the jQuery objects inside that, but it’s just one unnecessary step when you already have a perfectly good object to work with.

    Just thought I’d share my “discovery” today, haha.


    I just have some questions, if you wouldn’t mind explaining further. Thanks.

    “It’s a very messy way of working on things and you’re also giving some of your control away.”
    How so?

    “You should be working within your own objects and your own namespace, not jQuery’s.”

    “You may be creating memory leaks all over the place, but you wouldn’t know since you (I’m assuming here) don’t actually know what jQuery is doing.”
    Do YOU know what it is doing?


    I think you both made valid points. I don’t feel safe adding my properties and methods to an object created by another library, so i store jQuery elements like so:

    var menu = {
    $: $(‘#menu’),
    prop: value


    Interestingly enough though I saw memory leaks mentioned somewhere and a quest to learn more lead me here. I’m fairly certain that none of the code above would cause memory leaks my my definition (a memory leak keeps growing IMO, not simple be maintained across the life of a page) some articles though, stated storing DOM objects to variables inside closers = the most common cause for leaks.

Viewing 3 posts - 1 through 3 (of 3 total)
  • The forum ‘JavaScript’ is closed to new topics and replies.