Wednesday, September 25, 2019

Using closures to achieve privacy

Unlike most object-oriented programming languages, JavaScript does not support access modifiers such as, private, protected, and public to specify the accessibility of properties and methods in objects. In JavaScript, all object members are public. 
In the following example, both the author property and the getAuthor() method are public and therefore can be accessed from anywhere in the program.
  1. var book = {
  2. author: "James Joyce",
  3. getAuthor: function () {
  4. return this.author;
  5. }
  6. };
  7. alert(book.author); // => James Joyce (public property)
  8. alert(book.getAuthor()); // => James Joyce (public method)
Run
You may think that this is because we are using an object literal to create the book instance. However, creating an instance using a Book constructor function will also result in public properties and public methods as the following example demonstrates.
  1. function Book () {
  2. this.author = "James Joyce";
  3. this.getAuthor = function() {
  4. return this.author;
  5. }
  6. }
  7. var book = new Book();
  8. alert(book.author); // => James Joyce (public property)
  9. alert(book.getAuthor()); // => James Joyce (public method)
Run
With object members being so exposed, is there perhaps a way to protect these in JavaScript? The answer is yes, by using function closures.
Going back to the Book example, the objective is to keep the author data private without exposing it to the outside world. 
The way to do this is to define an author variable within the function. The functions closure ensures that it is only accessible within the function's scope. So, instead of assigning author to this, you create a local variable called author.
  1. function Book () {
  2. var author = "James Joyce"; // private
  3. this.getAuthor = function() { // privileged
  4. return author;
  5. }
  6. }
  7. var book = new Book();
  8. alert(book.author); // => undefined (i.e. private)
  9. alert(book.getAuthor()); // => "James Joyce"
Run
Closure is an important and powerful concept in JavaScript. Here it allows us to keep author private. The getAuthor() method is called a privileged method because it has access to the private author variable and is itself accessible to the outside world as a public method on the book instance.

No comments:

Post a Comment