Recently I posted my findings about private fields in JavaScript. So this is a continuation of the post and it talks about public fields in your JavaScript code. So here is a quick example of public properties in your code:
function User() { // Private property var name = ''; return { // Public property classVersion: '1.3', prevVersions: ['1.2.3', '1.2', '1'], setName: function(newName) { name = newName; }, getName: function() { return name; } }; } var user = new User(); user.classVersion; // 1.3 user.prevVersions; // ['1.2.3', '1.2', '1']
NOTE:
Define an object property name in your return statement and it will be accessible from outside. In other words - public field.
Public and private methods in JavaScript
I have been talking about public and private properties so far. I guess it is time for private and public methods. The idea behind is the same. To make a method public you need to define it in your return object and if you want to make it private you should declare it outside your return.
Basically:
function User() { // Private variable var name; // Private method var privateMethod = function(){ // Access to private fields name += " Changed"; }; return { // Public methods setName: function(newName) { name = newName; privateMethod(); }, getName: function() { return name; } }; } var user = new User(); user.setName("My Name"); user.getName(); // My Name Changed
As you can see, privateMethod
and name
are declared outside the return
object and thus they are made private. Variables declared inside the return object are public and accessible using dot notation.