0

Possible Duplicate:
JavaScript private methods

I was kind of busy playing with jquery, Ext JS, ...etc. that I never required to do this. So, I doubt if I am right.

The question is:

Create a Person class with public/private/privileged members and methods.

My solution is:

function Person () {
    var privatemember; //I wonder if there is any other way
    this.publicmember = null;
    this.privilegedmember = function (){
        //anything here
    }
}
Person.prototype.sayHi = function(){
    "Hi";
}

Please correct me if I am wrong, also explain individual in detail

Thanks.

Community
  • 1
  • 1
hrishikeshp19
  • 8,838
  • 26
  • 78
  • 141

3 Answers3

0

You are looking for the module pattern with closures, try Douglas Crockford's article Private Members in JavaScript.

RobG
  • 142,382
  • 31
  • 172
  • 209
0

Yes, that is the Javascript way. In truth, there are no "classes" in javascript. Every object is unique. It's like a dictionary (in other languages) which allows you to create unlimited key/value pairs.

There is however the prototype mechanism which allows for one object to be a "prototype" for another object. In this case, if a property is not found on the original object, then the prototype is searched for that property (and the prototype's prototype, etc.) But both objects are still individual and unique. This is nothing like the "class" mechanism found in C++ derived languages (like Java or C#), and attempting to emulate that will bring you many headaches.

Also yes, there is also nothing like the private/public/protected members. Your approach is correct - you can get hidden data by using closures. This enables something similar to "private" and "public". Unfortunately there is nothing to emulate the "protected" level (accessible only by this object and those for whom it is a prototype).

This brings to memory an interesting video about Javascript performance. The guys there had found out that (at least in the case of web browsers) the sheer amount of Javascript code can pretty quickly become a performance limiting factor. So it's often better to just make most of your variables public than to go with the OOP mantra of "private member - public accesors". It's less code and thus faster.

Vilx-
  • 104,512
  • 87
  • 279
  • 422
0

Javascript only have public members.

You can emulate "private" by closure using local variable as mentioned by @RobG.

You can, in Ecmascript 5 (== not old browser) make member non-writable and/or non-enumerable or the object structure itself non-changeable by judicious use of Object.defineProperty, seal, freeze and preventExtension. The model of "public members only" is still there, you only change the means of manipulating it.