Question

If I'm using some private functions in a class do certain naming conventions yield better performance or offer different functionality...or is it simply a matter of preference?

var MyClass = function() {

   var private1 = function(msg){
       // Do stuff.
       console.log(msg);
   };

   this.private2 = function(msg) {
       // Do stuff.
       console.log(msg);
   };

};
Was it helpful?

Solution

Your two variables have very different access so which one to use depends upon which type of access you want to offer, not just a coding style preference.

In your example, private1 is a local variable to your constructor and is ONLY available to code inside the constructor. It is NOT available to any code outside the constructor. It is actually private.

var yourObj = new MyClass();
yourObj.private1();   // undefined, will not work

private2 is an instance variable of a MyClass object you create with the new operator and is reachable by any code as yourObj.private2(). It is not private in any way - it is a publicly reachable method. Example:

var yourObj = new MyClass();
yourObj.private2();     // works

So private1 is private and private2 is public. One should select the implementation method that matches the desired goal of the code. This is not just a coding style preference.

OTHER TIPS

private1 is a function inside constructor MyClass and private2 is function of MyClass instance:

var cl = new MyClass();
console.log(cl.private1); // undefined
console.log(cl.private2); // function
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top