Search code examples
javascriptoopparametersprivate

Javascript private variables and parameters what is the difference?


While creating some objects in javascript I started to wonder if there is any point to create private variables that just point to the parameters since all the functions in an object (that can use the private variables) is inside the object function in javascript.

Example: I usually do like this

function Foo(a) {
   var _a = a;
   function something() {
      _a += 1;
      somethingElse(_a);
   }
}

But to me it seems like I could just do like this instead:

function Foo(a) {
   function something() {
      a += 1;
      somethingElse(a);
   }
}

My question then is, is there something that I am missing here or doing wrong or is this a good way to design my javascript objects?


Solution

  • My question then is, is there something that I am missing here or doing wrong or is this a good way to design my javascript objects?

    Functionally, there's no difference in your examples except that with the _a, you have an extra variable you don't really need.

    In loose mode, there may be a tiny performance difference, because writing to an argument requires not only updating the named copy (a), but the arguments pseudo-array as well. In strict mode, the two (the named version and the entry in arguments) are not linked and so you don't have that tiny potential performance difference.

    Of course, this is JavaScript, and optimizations vary across engines. A quick test, for instance, shows zero difference on Chrome and using the argument being very slightly slower on Firefox. Using the strict version, the difference on Firefox goes away (but it was so small it could easily be measurement error). (An earlier copy of this answer said one of them was slower on IE8, but I believe that was measurement error as I couldn't replicate the result.)

    I wouldn't expect the difference in speed to matter regardless, unless you are calling something a huge number of times.