0

Let's look on this JavaScript code:

Person: function() {
    var element = null;

    this.init = function() {
        // select an HTML element created+ added to DOM in init()
        element = $("#justCreatedElement"); 
    };

    this.workingFunction = function() {
        // use private member `element`
        element;

        // create new variable and select again with jquery
        var element = $("#justCreatedElement");
    }
}

We can assume that the init() method gets called before any other method.

I have the following Question:

1 In the init() I use JQuery to assign a HTML element to the private member element. Because element is visible for all methods I can just use it again in the method workingFunction2(). What is better coding standard:

I Using element private member in all member mehtods and even maybe write it in any member methof.

II Using element private member only to read in all member methods, except once, where it is set for the first time, here in init(). And if private member element must be changed use a mehtod called changeELement() but do not write it in a method where the user cannot know that it get written to.

III General avoid to use a member variable that holds JQuery selections and always select again in every mehtod

Or can somebody give me his own standards regarding this problem.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Viktor Carlson
  • 989
  • 1
  • 13
  • 36
  • *"What is better coding standard...?"* Neither. Both. It completely depends on other factors. What's the cost of re-querying the DOM for the element? (With `getElementById`, it's really small; other queries can be more expense.) How often would you re-query if you re-queried? Will anything else *completely replace* the element? Are you doing this with tens of thousands of instances? I'm not actually asking you these questions, I'm just pointing out that the answer here is: "It depends." – T.J. Crowder Aug 03 '16 at 11:04
  • It is in general a good Idea when working with a dedicated elements on differend places over-and-over again to store it in a variable. Regardless if working with plain JS or jQuery. But as @T.J.Crowder said before: "It depends". ;) – eisbehr Aug 03 '16 at 11:05
  • Possible duplicate of [Does jQuery do any kind of caching of "selectors"?](http://stackoverflow.com/questions/291841/does-jquery-do-any-kind-of-caching-of-selectors) – Dekel Aug 03 '16 at 12:27

0 Answers0