What is the benefit of using private methods?


#1

Can somebody please explain why a private method is necessary.

Since it is the programmer who decides to declare the bankBalance property using 'var' rather than 'this', why should he not declare using 'this' and then this would mean it a private method is unnecessary?


#2

Well we're getting into SUPER SPECIFIC ULTRA MEGA AWESOME PROGRAMMING mode here, so if you don't understand something that I'm saying please just quote me on it and I'll be sure to explain it in greater detail.

I'm assuming by now you understand the difference between private and public variables and how they work differently from eachother, as in one is not able to be called from outside the method and one is, so I'm going to jump right into an example if that's ok with you.

IF YOU DON'T WANT TO READ EVERYTHING JUST GO TO THE LAST PARAGRAPH!


So Mr. Programmer is working on a project and his supervisor Mr. Manager comes up to see what he's working on. As it turns out, Mr. Programmer was making a method about calculating trigonometry. Unfortunately there's not that many helpful trig functions in JavaScript so Mr. Programmer starts making them from scratch.

Mr. Programmer has a bunch of different functions in his object that help him calculate trig functions in similar ways. Unfortunately he needs to use variables that only the function can see to help him out with the calculations, and he doesn't want to have to type all of the calculations over and over again.

Now Mr. Programmer has an idea! He thinks "Hey, why don't I use a PRIVATE VARIABLES to help me!" Mr. Programmer knows that he can't just use public variables. What if he accidentally calls them when he means to call a variable of a similar likeness!

Moral of the story is that Mr. Programmer uses public variables to call and set properties for the trig function to process, and uses PRIVATE variables to modify and process the public variables without being able to be changed by outside sources. (Such as the user!)


#3

I hope this helps!

If you have any other questions please don't hesitate to ask. I'll help as much as possible.