Is there any way to make “private” variables (those defined in the constructor), available to prototype-defined methods?
TestClass = function(){
var priv
You can actually achieve this by using Accessor Verification:
(function(key, global) {
// Creates a private data accessor function.
function _(pData) {
return function(aKey) {
return aKey === key && pData;
};
}
// Private data accessor verifier. Verifies by making sure that the string
// version of the function looks normal and that the toString function hasn't
// been modified. NOTE: Verification can be duped if the rogue code replaces
// Function.prototype.toString before this closure executes.
function $(me) {
if(me._ + '' == _asString && me._.toString === _toString) {
return me._(key);
}
}
var _asString = _({}) + '', _toString = _.toString;
// Creates a Person class.
var PersonPrototype = (global.Person = function(firstName, lastName) {
this._ = _({
firstName : firstName,
lastName : lastName
});
}).prototype;
PersonPrototype.getName = function() {
var pData = $(this);
return pData.firstName + ' ' + pData.lastName;
};
PersonPrototype.setFirstName = function(firstName) {
var pData = $(this);
pData.firstName = firstName;
return this;
};
PersonPrototype.setLastName = function(lastName) {
var pData = $(this);
pData.lastName = lastName;
return this;
};
})({}, this);
var chris = new Person('Chris', 'West');
alert(chris.setFirstName('Christopher').setLastName('Webber').getName());
This example comes from my post about Prototypal Functions & Private Data and is explained in more detail there.
Try it!
function Potatoe(size) {
var _image = new Image();
_image.src = 'potatoe_'+size+'.png';
function getImage() {
if (getImage.caller == null || getImage.caller.owner != Potatoe.prototype)
throw new Error('This is a private property.');
return _image;
}
Object.defineProperty(this,'image',{
configurable: false,
enumerable: false,
get : getImage
});
Object.defineProperty(this,'size',{
writable: false,
configurable: false,
enumerable: true,
value : size
});
}
Potatoe.prototype.draw = function(ctx,x,y) {
//ctx.drawImage(this.image,x,y);
console.log(this.image);
}
Potatoe.prototype.draw.owner = Potatoe.prototype;
var pot = new Potatoe(32);
console.log('Potatoe size: '+pot.size);
try {
console.log('Potatoe image: '+pot.image);
} catch(e) {
console.log('Oops: '+e);
}
pot.draw();
There is a very simple way to do this
function SharedPrivate(){
var private = "secret";
this.constructor.prototype.getP = function(){return private}
this.constructor.prototype.setP = function(v){ private = v;}
}
var o1 = new SharedPrivate();
var o2 = new SharedPrivate();
console.log(o1.getP()); // secret
console.log(o2.getP()); // secret
o1.setP("Pentax Full Frame K1 is on sale..!");
console.log(o1.getP()); // Pentax Full Frame K1 is on sale..!
console.log(o2.getP()); // Pentax Full Frame K1 is on sale..!
o2.setP("And it's only for $1,795._");
console.log(o1.getP()); // And it's only for $1,795._
JavaScript prototypes are golden.
I suggest it would probably be a good idea to describe "having a prototype assignment in a constructor" as a Javascript anti-pattern. Think about it. It is way too risky.
What you're actually doing there on creation of the second object (i.e. b) is redefining that prototype function for all objects that use that prototype. This will effectively reset the value for object a in your example. It will work if you want a shared variable and if you happen to create all of the object instances up front, but it feels way too risky.
I found a bug in some Javascript I was working on recently that was due to this exact anti-pattern. It was trying to set a drag and drop handler on the particular object being created but was instead doing it for all instances. Not good.
Doug Crockford's solution is the best.
Was playing around with this today and this was the only solution I could find without using Symbols. Best thing about this is it can actually all be completely private.
The solution is based around a homegrown module loader which basically becomes the mediator for a private storage cache (using a weak map).
const loader = (function() {
function ModuleLoader() {}
//Static, accessible only if truly needed through obj.constructor.modules
//Can also be made completely private by removing the ModuleLoader prefix.
ModuleLoader.modulesLoaded = 0;
ModuleLoader.modules = {}
ModuleLoader.prototype.define = function(moduleName, dModule) {
if (moduleName in ModuleLoader.modules) throw new Error('Error, duplicate module');
const module = ModuleLoader.modules[moduleName] = {}
module.context = {
__moduleName: moduleName,
exports: {}
}
//Weak map with instance as the key, when the created instance is garbage collected or goes out of scope this will be cleaned up.
module._private = {
private_sections: new WeakMap(),
instances: []
};
function private(action, instance) {
switch (action) {
case "create":
if (module._private.private_sections.has(instance)) throw new Error('Cannot create private store twice on the same instance! check calls to create.')
module._private.instances.push(instance);
module._private.private_sections.set(instance, {});
break;
case "delete":
const index = module._private.instances.indexOf(instance);
if (index == -1) throw new Error('Invalid state');
module._private.instances.slice(index, 1);
return module._private.private_sections.delete(instance);
break;
case "get":
return module._private.private_sections.get(instance);
break;
default:
throw new Error('Invalid action');
break;
}
}
dModule.call(module.context, private);
ModuleLoader.modulesLoaded++;
}
ModuleLoader.prototype.remove = function(moduleName) {
if (!moduleName in (ModuleLoader.modules)) return;
/*
Clean up as best we can.
*/
const module = ModuleLoader.modules[moduleName];
module.context.__moduleName = null;
module.context.exports = null;
module.cotext = null;
module._private.instances.forEach(function(instance) { module._private.private_sections.delete(instance) });
for (let i = 0; i < module._private.instances.length; i++) {
module._private.instances[i] = undefined;
}
module._private.instances = undefined;
module._private = null;
delete ModuleLoader.modules[moduleName];
ModuleLoader.modulesLoaded -= 1;
}
ModuleLoader.prototype.require = function(moduleName) {
if (!(moduleName in ModuleLoader.modules)) throw new Error('Module does not exist');
return ModuleLoader.modules[moduleName].context.exports;
}
return new ModuleLoader();
})();
loader.define('MyModule', function(private_store) {
function MyClass() {
//Creates the private storage facility. Called once in constructor.
private_store("create", this);
//Retrieve the private storage object from the storage facility.
private_store("get", this).no = 1;
}
MyClass.prototype.incrementPrivateVar = function() {
private_store("get", this).no += 1;
}
MyClass.prototype.getPrivateVar = function() {
return private_store("get", this).no;
}
this.exports = MyClass;
})
//Get whatever is exported from MyModule
const MyClass = loader.require('MyModule');
//Create a new instance of `MyClass`
const myClass = new MyClass();
//Create another instance of `MyClass`
const myClass2 = new MyClass();
//print out current private vars
console.log('pVar = ' + myClass.getPrivateVar())
console.log('pVar2 = ' + myClass2.getPrivateVar())
//Increment it
myClass.incrementPrivateVar()
//Print out to see if one affected the other or shared
console.log('pVar after increment = ' + myClass.getPrivateVar())
console.log('pVar after increment on other class = ' + myClass2.getPrivateVar())
//Clean up.
loader.remove('MyModule')
see Doug Crockford's page on this. You have to do it indirectly with something that can access the scope of the private variable.
another example:
Incrementer = function(init) {
var counter = init || 0; // "counter" is a private variable
this._increment = function() { return counter++; }
this._set = function(x) { counter = x; }
}
Incrementer.prototype.increment = function() { return this._increment(); }
Incrementer.prototype.set = function(x) { return this._set(x); }
use case:
js>i = new Incrementer(100);
[object Object]
js>i.increment()
100
js>i.increment()
101
js>i.increment()
102
js>i.increment()
103
js>i.set(-44)
js>i.increment()
-44
js>i.increment()
-43
js>i.increment()
-42