Private and Protected members

Private and Protected members

by Nirvanachain

HTML

<a href="http://philipwalton.com/articles/implementing-private-and-protected-members-in-javascript/?utm_source=javascriptweekly&utm_medium=email" target="_blank">Helpful Article</a>

JavaScript

var Car = (function () {
    
    // create a store to hold private objects
    var privateStore = {},
        uid = 0;
    
    function Car(mileage) {
        // Create an object to manage this objects state
        // and use a unique ID to reference it in the
        // private store
        privateStore[this.id = uid++] = {};

        // Store private stuff in the private store
        // instead of this.
        privateStore[this.id].mileage || 0;
    }
    
    Car.prototype.drive = function (miles) {
        if (typeof miles == 'number' && miles > 0) {
            privateStore[this.id].mileage += miles;
        } else {
            throw new Error('drive can only accept positive numbers');   
        }
    }
    
    Car.prototype.readMileage = function () {
        return privateStore[this.id].mileage;   
    }
    
    return Car;
}());