views:

135

answers:

2

I am a new programmer, and I started in C and am now starting to enjoy JavaScript and a tiny bit of PHP more. Lately I've heard the terms 'private' and 'public' functions a lot. Could anybody give an explanation of the both and how they are of use to a programmer?

And I'm probably totally wrong here... but is a

(function(){}) 

in javascript a private function?

+1  A: 

public members can be accessed from outside the class they were declared in, private members can only be accessed from within the class they were declared in. Private members are commonly manipulated through get/set methods, which allows for greater encapsulation and hides the implementation from the calling function.

We use these keywords to specify access levels for member variables, or for member functions (methods). Public variables, are variables that are visible to all classes. Private variables, are variables that are visible only to the class to which they belong. Protected variables, are variables that are visible only to the class to which they belong, and any subclasses. Deciding when to use private, protected, or public variables is sometimes tricky. You need to think whether or not an external object (or program), actually needs direct access to the information. If you do want other objects to access internal data, but wish to control it, you would make it either private or protected, but provide functions which can manipulate the data in a controlled way

Fatih
Uhh ... what do the `private`, `protected`, and `public` keywords have to do with Javascript?
Pointy
It's okay, I'm trying to get an idea of the practice as a whole.
Kyle
OK then - I think his comments are fine if you're looking at Java - but remember that almost the only things common between "Java" and "Javascript" are those 4 letters :-)
Pointy
@Pointy: they do also both use the term "object", for reasons I have yet to discover...
SamB
Well, "object" seems OK to me as a word to use for the things in each language that it's used for, but you're right that the things themselves are so different that the shared terminology can be confusing.
Pointy
+8  A: 
Pointy
+1 For the method name x.getMyPrivates(), I'm <sarcastic>12</sarcastic> heheh.
leeand00