Click here to Skip to main content
Rate this: bad
good
Please Sign up or sign in to vote.
See more: Javascript
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 9: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
0 Sergey Alexandrovich Kryukov 575
1 Kornfeld Eliyahu Peter 409
2 Maciej Los 369
3 DamithSL 196
4 OriginalGriff 188
0 OriginalGriff 6,353
1 DamithSL 4,854
2 Maciej Los 4,476
3 Kornfeld Eliyahu Peter 4,058
4 Sergey Alexandrovich Kryukov 3,917


Advertise | Privacy | Mobile
Web02 | 2.8.141220.1 | Last Updated 24 Jan 2013
Copyright © CodeProject, 1999-2014
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