In the first case, an object built using new RobsObject() has the functions _onSubmit() , _onSuccess() as properties. These are the so-called public functions of the object.
In the second case, these functions are not properties of new RobsObject() . However, they will be visible to any of the "public" functions (in your case they are not). In essence, these are private functions.
However, if you wrote your second snippet this way ...
RobsObject = function(data){ this.instanceID = data.instanceID; this._formButton = document.getElementById('formSubmit_' + this.instanceID); if(this._formButton) { //set a click listener that //points to this._onSubmit, this._onSuccess, and this.onFailure } this._onSubmit = function(type, args) { //make an ajax call } this._onSuccess = function(type, args) { //display data on the page } this._onFailure = function(type, args) { //show an alert of some kind } };
The result is the same.
An important difference between the two conventions is that in the first method you cannot define private functions that can be shared between many public functions, as in the second method. The object literal used to define the prototype does not form closures similar to the body of a function.
For instance,
function MyConstructor() { var myPrivate = function() { } this.myPublic1 = function() { myPrivate(); } this.myPublic2 = function() { myPrivate(); } }
myPrivate() is a function that is visible to both public functions.
source share