Public or Private? Why make your life harder than it has to be?


#1

Just like the scope I am having a hard time wrapping my mind around this. I have a couple of questions.
1. When something is private it is only accessible withing the class . I thought the class included the constructor and all of the objects created with its prototype . If its just the constructor then why not just call it that (a constructor)
2. What is the point of making something private?


#2

@williab3,

function CarClass(carType,wheels) {
    this.carType = carType;
    this.wheels = wheels;
    var carOperator = "robot";
    this.setCarOp = function(newCarOperator) {
        //console.log("carOperator-old: "+carOperator);
       carOperator = newCarOperator;
        //console.log("carOperator-new: "+carOperator);
    };
    this.getCarOp = function() {
        console.log( carOperator );
    };
}

//create an Instance of CarClass
var myObj = new CarClass("sedan",4,"robot");
console.log( window.carOperator );
//property =carOperator= is not publicly accessable
console.log( myObj );

//use the =getter-Method=
//to get at the property-Value 
myObj.getCarOp();

//use the =setter-Method=
//to set a new property-Value
myObj.setCarOp( "human" );
myObj.getCarOp();

=======

== discussion / opinions ==
= http://stackoverflow.com/questions/22156326/private-properties-in-javascript-es6-classes


#3

:expressionless:

I'm not quite sure what to say. I just want to know what are the practical reasons of making something private.
Can you explain how that link or the program helps me understand because I completely missed it.


#4

Probably one of the best reasons I can think of is to stop information leaking around you program.

Supposing you have a loop that calls another function that has another loop in it. You don't want the second loop accessing the counter variable from the first loop or vice verca.

In my opinion, it's generally safer to keep variable private unless you have a specific reason to need them all over your program. The larger and more complex your program is the more important this becomes