There is an important and useful difference between these syntaxes.
Encapsulation
In OOP, it is very useful to use encapsulation, which is a mechanism for restricting access to other objects. The difference between public and private vars / functions in javascript can be formulated as follows:
function Color(value) { // public variable this.value = value; // get from arguments // private variable var _name = "test"; // public function this.getRandomColor = function( ) { return Math.random() * 0xFFFFFF; } // private function function getNiceColor() { return 0xffcc00; } }
Public Testing
Public variables and functions are available inside the color instance:
// create instance of Color var color = new Color(0xFF0000); alert( color.value ); // returns red color alert( color.getRandomColor() ); // returns random color
Testing Private
Private variables and functions cannot be accessed from the color instance:
var color = new Color(0x0000FF); alert( color.getNiceColor() ); // error in console; property does not exist, because function is private. alert( color._name ); // error in console; property does not exist, because variable is private.
Note
It is better to use good prototypes when using public functions, because this encoding method can cause inheritance problems.
source share