Using closures to achieve privacy Among JavaScript Objects.[Like Public,Protect,Private] in OOP'S

Posted by Prabhukiran345 under JavaScript category on | Points: 40 | Views : 411
1) 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.

But We can implement this by using function closures .

function Book () {
var author = "Prabhu Kiran"; // private
this.getAuthor = function() { // privileged
return author;
var book = new Book();

alert(; // => undefined (i.e. private)
alert(book.getAuthor()); // => "Prabhu Kiran"

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.

Comments or Responses

Login to post response