Click here to Skip to main content
12,948,385 members (70,278 online)
Rate this:
 
Please Sign up or sign in to vote.
See more:
I'm using an implementation of base.js from here: http://ejohn.org/blog/simple-javascript-inheritance/

I attempted to combine this with sandboxing to get "private" variables. For example:

// Sandbox.
(function () {
 
var privateVar;
 
myClass = Class.extend({
    init: function (bindingOptions) {
        privateVar = 0;
    },
 
getPrivateVar: function() {
    return privateVar;
},
 
setPrivateVar: function(value) {
    privateVar = value;
});
})();

However, when I try to make 2 instances, of course the "privateVar" has the same value. For example:

var class1 = new myClass();
var class2 = new myClass();
class1.setPrivateVar(5); // now both class1 and class2 report privateVar as "5"

Is there any way to get private variables using this methodology that are scoped to the object without resorting to "this._privateField" ?
Posted 24-Jan-13 8:24am
Rate this: bad
 
good
Please Sign up or sign in to vote.

Solution 2

After further research, the answer here is that it isn't possible.

Reference: http://robertnyman.com/2008/10/21/javascript-inheritance-experimenting-with-syntax-alternatives-and-private-variables/[^]

The reason is that if you use the sandboxing methodology I outlined above, any "private" variable declared will be static. Methods, however, can successfully be hidden and work.
  Permalink  
Rate this: bad
 
good
Please Sign up or sign in to vote.

Solution 1

If you want instance specific private variables,


 
function ClassConstructor(...) {
var that = this;
var membername = value;
function privatememthod(...) {...}
 
}
 


you have instance specific private variable membername & private method privatemethod.

Access for external methods:

 
function ClassConstructor(...) {
var that = this;
var membername = value;
function privatememthod(...) {...}
 
return {
  getPrivareMember: function(){
       return membername;
  }
}
}
 
  Permalink  
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

    Print Answers RSS
Top Experts
Last 24hrsThis month
OriginalGriff 5,344
CHill60 3,275
Maciej Los 2,703
Jochen Arndt 1,935
ppolymorphe 1,795


Advertise | Privacy | Mobile
Web02 | 2.8.170524.1 | Last Updated 24 Jan 2013
Copyright © CodeProject, 1999-2017
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100