Click here to Skip to main content
11,581,510 members (64,678 online)
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 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
0 OriginalGriff 340
1 Sergey Alexandrovich Kryukov 160
2 Frankie-C 105
3 RyanDev 84
4 virusstorm 84
0 OriginalGriff 1,273
1 Sergey Alexandrovich Kryukov 900
2 Abhinav S 617
3 F-ES Sitecore 500
4 Suvendu Shekhar Giri 433


Advertise | Privacy | Mobile
Web03 | 2.8.150603.1 | Last Updated 24 Jan 2013
Copyright © CodeProject, 1999-2015
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