Click here to Skip to main content
11,709,537 members (46,875 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 Sergey Alexandrovich Kryukov 530
1 OriginalGriff 250
2 Peter Leow 229
3 Maciej Los 185
4 Mika Wendelius 160
0 OriginalGriff 9,428
1 Sergey Alexandrovich Kryukov 9,037
2 CPallini 5,189
3 Maciej Los 4,991
4 Mika Wendelius 3,856


Advertise | Privacy | Mobile
Web02 | 2.8.150819.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