Thursday, May 5, 2011

javascript object oriented programming 4 - private members

Let's check the code:
Car = {
   model : 'mazda 3',
   getModel : function() {return this.model},
}
//we can access the model property directly
console.log(Car.model);
//how about we use function constructor?
var Car = function() {
    this.model = 'mazda 3';
}
var newCar = new Car;
//we still can access the model property directly.
console.log(newCar.model);


In the above examples, we can't hide object's properties from being exposed. What if we want to have private properties and private methods/functions that can be accessed only in the object, just like what we do in java and php 5?

Same as we use object scope to achieve namespace, we can also create private members for our object.
var Car = function() {
    //the model variable is only visible within the Car object now!
   //so it becomes a private property of Car
    var model = 'mazda 3';
    //since function, which is object in js, can be assigned to a variable,
    //we can have private function too!
   // this upgrade function is only visible in Car scope!
    var upgrade = function(newModel) {
        model = newModel;
    };
    //a public method.
    this.getModel = function() {
        upgrade('mazda 6');
        return model;
    }
}
var newCar = new Car();
//will get undefined
console.log(newCar.model);
//will get error
newCar.upgrade('toyota');
//will get mazda 6
newCar.getModel();


Some people say javascript is a functional programming language, some argue it is object based language because almost everything is object in javascript, while others prove that javascript can have full OOP features just like other modern object oriented programming languages like java. 

I would say, javascript is a plasticine programming language! You can shape it as whatever you want !

Actually, i think we don't even need to bother about implementing those private member stuff. If we really want to have private, we can simply use naming convention: private members must be prefixed with underscore, for example:
var Car = function() {
    this._model = '3';
    this._upgrade = function(newModel) {
        this._model = newModel;
    };
    this.getModel = function() {
        this._upgrade('mazda 6');
        return this._model;
    }
}

And then, just tell your team members to follow this coding convention: when you see something prefixed with _, you know you shall not directly access it or change its status.

No comments: