The second code sample is the proper way to achieve what you're looking for. You create an immediately-executing function, inside of which you create a new function, add to its prototype, and then return it.
The first example is a bit odd, and doesn't quite create a constructor function properly. The line
return Car.prototype; // return with prototype
causes your Car function to simply always return the object literal that you had previously assigned to Car.prototype
. This overrides the normal behavior of a function invoked with new
Just one thing to note, this line:
Car.prototype = {
newColor: function(color) { private.color = color },
getColor: function() { return private.color }
};
will cause the constructor
property of newly create objects to no longer point to your Car function. There are two easy ways to fix this if this is important to you.
Car.prototype = {
newColor: function(color) { private.color = color },
getColor: function() { return private.color }
};
Car.prototype.constructor = Car; // <-------- add this line
Or change the above to
Car.prototype.newColor = function(color) { private.color = color };
Car.prototype.getColor = function() { return private.color };