Is there any way to make “private” variables (those defined in the constructor), available to prototype-defined methods?
TestClass = function(){
var priv
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();