Saturday, May 7, 2011

javascript object oriented programming 5 - private members 2(object literal)

My last blog shows how to achieve privacy for objects using function constructors. How about object literals?

Check the code:

//this is the object
var newCar;

//now, let js's anonymous immediate function do the trick
(function() {
//private members
var model = 'mazda 3';

//public implementation
//don't put 'var' before the newCar!
newCar = {
     getModel : function(){return model;}
};
}());

//now, let's call the getModel method, 
//you will get 'mazda 3'
newCar.getModel();


The way it works is easy to understand as long as we know, javascript object and function can provide local scope. So we just need a function to wrap the private data. In object literals, we can use the closure created by an additional anonymous immediate function.

But do we really want to create object privacy in this way? For me, this kind of code cannot be counted elegant. My last blog suggests we can simply use naming convention to achieve object privacy. It sounds not professional, but i believe that is the easiest way: easy to implement, easy to read, easy to understand, easy to modify.

Let's accept this truth: javascript is NOT especially designed as an object oriented programming language, it is  NOT  especially designed for OOP, even though it provides with the power/magic/flexibility that you can make it an OOP language or achieve all OOP language features.

I still believe the best word to describe javascript is plasticine. You can shape it and make it look like different things.

I have to declare that I am not against using javascript to do OOP. Actually, i believe we should apply OOA/OOP to any complicated and large javascript project, a web game, for example. But i don't think it is necessary that we twist javascript to prove that it is a fully OOP language.

No comments: