Click here to Skip to main content
15,887,379 members
Please Sign up or sign in to vote.
5.00/5 (1 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:

JavaScript
// 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:

JavaScript
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

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.
 
Share this answer
 
If you want instance specific private variables,


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

}


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

Access for external methods:

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

return {
  getPrivareMember: function(){
       return membername;
  }
}
}
 
Share this answer
 
v2

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



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900