Make Object Properties Private missunderstanding

Hi guys,
I can’t understand what happens in the (( Make Object Properties Private
)) or what I suppose to understand? Can anyone help, please?

This is JS’s version of object oriented programming. You are going to have an object and it will have private properties. For example, I could have an object:

var Oven = function() {
   var temp = 350;
};

The idea is that temp can’t be accessed directly. It is invisible. It is private to that object. You need a function to access it. Very common functions are getters and setters:

var Oven = function() {
  
  var temp;

  this.getTemp = function() {
    return this.temp;
  };

  this.setTemp = function(newTemp) {
    this.temp = newTemp;
  };
  
};

Now, the only way to access temp is through the setter and getter functions. [EDIT: It would have been better to say “Now, in a true object oriented language, the only way to access temp is through the setter and getter function.” - thank you ppc] Why would you want to do that? It’s kind of hard to explain, but in more complicated programs with many writers, maybe you want to control how they access those variables. For example, maybe you want to make sure that they only set the temp to a number between 200 and 500, rounded off to the nearest 10. You could also prevent someone from setting it to undefined or "aardvark".

2 Likes

The Oven example above does not prevent access to the temp property

Try

let o=new Oven()
o.setTemp(5)
o.temp

There are ways to make it hard to access an object property - none is straightforward

1 Like

Hi Ahmed,
I think that technically it works so that because speed is declared inside the Car object using var keyword it’s scope is only inside that object, it’s like a local variable to Car - not visible outside to read/write. You can’t create a new car instance and directly set its speed to some value like
some_car.speed = 900;
as you could if you had created it as a public property using this keyword. You can only access it via the three public methods.

As ksjazzguitar said it prevents users setting object’s instances to crazy values. Say you have a Person class and you want to ensure age property is a valid number, say between 0 -120. So you would make age a private property and create a public setAge method which checks if the new value is valid and if it isn’t doesn’t perform the change.

var Person = function() {
   var age = 35;
   this.setAge = function(newAge) {
       if (newAge >= 0 && newAge <= 120) {
           age = newAge;
        }
      };
      //other code
 };

You might also want to keep a property private if you are for example storing it a particular format and your object have some methods that use the property in this format- then if someone changes it to something different, say a string, other parts might break down, etc.

1 Like

@ppc Yes, JS is not a true object oriented language. In a true OO language, it would be easy to hide the private properties and they would be completely inaccessible. I think there are some ways deeper in the language to have a hacky way to hide those properties, but for JS, it’s more of “OK, I’ve given you getters and setters so you’re on the honor system to not access these properties directly.” I’ve seen people precede the private property names with “private_”, so it would be o.private_temp to remind people. But for true OO behavior, we’d need another language. The YDKJS books do a good job of deconstructing the “JS can do OO” myth. It can sort of approximate some aspects.

The OP was asking about the specific problem. I gave and example and tried to explain the logic. I’m sorry if the statement “Now, the only way to access temp is through the setter and getter functions.” was incorrect - I was speaking more about the spirit of OO than than the JS approximation. I apologize for being unclear - I was focused too much on the specifics of what the OP was trying to understand and providing some of the logic of it.

2 Likes

Good answers on some of the specifics so far, but let’s take a step back because this is an important topic and it pays to have a solid foundation.

When we first start programming, we think of the programs starting at line 0 and working its way to the end of the file in a linear fashion. This is totally natural, and it’s how all programs used to be written. As computer hardware got more sophisticated, so too did the software, and with this sophistication came complexity. Software needed to be split up in ways that allowed teams of people to work on different parts independently of each other. Functions are the basis of code reuse, but there could be thousands of different functions at work in a large project and most of them shouldn’t be called by anyone. We needed a better way for code to be organized, and object oriented programming is a popular strategy for creating code that can be easily shared and reused.

One of the big ideas behind OOP is encapsulation. It’s a simple concept - you write code in modules that perform whatever functionality they need to do, and then you expose only the functions that another programmer may need in order to use your module. This is done by writing your code inside of classes and marking its variables and functions as either private or public. This can be made clear by example.

Let’s say that you and I are working on the same project. We’re making Instagram. You are working on the UI, and I’m writing the code that connects the UI to the user’s account. We both have complicated jobs. My code must log the user in, fetch their data from our database, send updates when the user clicks a button and so on. Your code must update the app when new data comes in, fetch new data when requested, take the user to different screens, and do everything efficiently. To make both of our jobs easier, we encapsulate our code and expose only the functions that are necessary to gluing our modules together. You would write a function called update. When I get the user’s initial data in, I can use it like this:

View.update(dataFromTheServer);

Your View module does a lot of stuff when it receives that data. It may render each photo, set a timer, populate the user’s likes, and who knows what else. I don’t care. It’s not my job to care. I don’t want to care. All I want is to write the code that fetches or sends user data, and I want to send this code to the UI as simply as possible. Likewise, you don’t know or care how I do my job, you just need a simple function like sendUpdatesToServer. My code will do a bunch of stuff when that function is called, but you just need that one function.

In the same vein, we don’t want to let anyone access all of the variables used in your module. Maybe you have a variable that keeps track of the number of times the user clicks a like button. You don’t want other programmers to be able to change that value because it will screw up your code. The OO solution is to make that variable private so the compiler doesn’t let anyone touch it. In fact, all variables should be private as good practice. This protects your code from misuse and communicates to other programmers what they should and shouldn’t touch. If someone needs to access a variable in your module, you should write a getter or setter method. This way you control access to all of your code.

So what does this have to do with the challenge Make Object Properties Private? Well, JavaScript wasn’t designed to fit into the object oriented model of programming. Java, Python, C++, and Ruby are all very much OO languages, but JavaScript is not. There is no way for us to mark a function or variable as private. But we can hide code, which is what the lesson is trying to show you. There are much better ways to encapsulate data, but that’s outside the scope of an already too long post.

Hope this helps.

6 Likes

That’s so helpful. Thank you for helping. :slight_smile:

I am not sure that i understand this !

Well, That’s a good answer but I have 2 questions about your code:
1- Is it necessary t use al of these semi-colons?
2- There is a missing this.getAge to return the value, Am I right?

Of course it helped. It wasn’t what I am asking for but, It is very valuable Information to now and I think it must be add at the challenge explaination to clearfy what the purpose of the challenge. But, for me it can be explained more simple because for biggener what you said is so advanced what makes me think that you are an expert programmer or junior at least. So, Thank you for help, it was special :slight_smile:

Thank you!
About this.getAge- yes, it would make sense if the class had some method that allows to use the age value. It is your choice though what method it is. As @PortableStick writes above about encapsulation- you decide what functionality your modules have- so if there is a case where someone from outside needs to access the age value of the Person instance you will write a this.getAge method or similar. But you could just as well only use the age only internally like so-
var Person = function() { var age = 35; //local variable, used only internally this.SetAge=function(newAge) { if(newAge >=0 && newAge <= 120) { age = newAge; } }; //public method, uses age variable to compute return value this.canIDrive = function() { if (age >= 18) { return "Yes, you are allowed to drive" } else { return "No, you're not allowed to drive" } }; };

About the semicolons- the code in my first post was meant only as an example how you can control what value age is set to; it does have some syntax errors though, thanks for pointing it out I will correct that.
`

2 Likes

Well, Thank you for clarifying this because, for a beginner like me, it confuses me. That’s better now. Thanks for your help.

I’m surprised no one has mentioned IIFs here, given that it is such a common pattern and a good way to keep vars private. It’s also a good way to minimize what gets added to the global scope.
(function(global){ global.coreObj = {}; var privateVar = 0; global.coreObj.publicFunction = function (){ console.log(privateVar); }; }(window);

1 Like