Javascript Object Oriented Design - Javascript Private Members for Constructors








The following code shows how to create custom types that require their own private properties.


function Book(name) { //from w  w  w .  j av a  2  s  . co m
    // define a variable only accessible inside of the Book constructor 
    var version = 1; 
    this.name = name; 
    this.getVersion = function() { 
        return versioin; 
    }; 
    this.publishNewNewsion = function() { 
       version++; 
    }; 
} 

var book = new Book("Javascript"); 

console.log(book.name);       // "Javascript" 
console.log(book.getVersion());   // 1

book.version = 2; 
console.log(book.getVersion());   // 1 

book.publishNewNewsion(); 
console.log(book.getVersion());   // 2

The code above generates the following result.





Example

To share private data across all instances:


var Book = (function() { 
    // everyone shares the same version
    var version = 1; 
/*from   ww  w  .j ava  2 s.  com*/
    function InnerBook(name) { 
        this.name = name; 
    } 
    InnerBook.prototype.getVersion = function() { 
        return version; 
    }; 
    InnerBook.prototype.publishNewVersion = function() { 
        version++; 
    }; 
    return InnerBook; 
}()); 

var book1 = new Book("Javascript"); 
var book2 = new Book("CSS"); 

console.log(book1.name);      // "Javascript" 
console.log(book1.getVersion());  // 1 

console.log(book2.name);      // "CSS" 
console.log(book2.getVersion());  // 1 

book1.publishNewVersion(); 
console.log(book1.getVersion());   // 2 
console.log(book2.getVersion());   // 2 

The code above generates the following result.