Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Create Protected Object Properties in JavaScript

Is there a JavaScript pattern which mimics "Protected" object properties like what you see in languages like C++ ??

Basically, I'd like to create an Object A which has a number of "protected" object properties which can be accessed ONLY from methods which are defined from the prototype of Object A. i.e. - NOT accessible publicly from non-prototyped methods of A.

For instance, ideally would be like so:

function A(){
    var prop1 = 1;      
}

A.prototype.myFunc = function(){
    var newVar = this.prop1;   //newVar now is equivalent to 1
}

var instanceOfA = new A();
var newVar2 = instanceOfA.prop1;  //error given as prop1 is "protected"; hence undefined in this case

BTW - I do not want the pattern of privileged member functions accessing private properties since the member function is still public.

like image 358
Drake Amara Avatar asked Nov 07 '11 23:11

Drake Amara


2 Answers

There is no object property that can only be accessed from prototyped methods of A and not from non-prototyped methods of A. The language doesn't have that type of feature and I'm not aware of any work-around/hack to implement it.

Using Doug Crockford's methods, you can create member properties that can only be accessed from predefined non-prototyped methods (those defined in the constructor). So, if you're trying to limit access only to a predefined set of methods, this will accomplish that. Other than that, I think you're out of luck.

If you want other ideas, you'd probably get more help if you describe more about what you're actually trying to accomplish in your code rather than just how to emulate a feature in another language. Javascript is so much different than C++ that it's better to start from the needs of the problem rather than try to find an analogy to some C++ feature.

like image 61
jfriend00 Avatar answered Oct 06 '22 00:10

jfriend00


You cannot do it in Javascript.

like image 43
Thomas Eding Avatar answered Oct 05 '22 23:10

Thomas Eding