views:

649

answers:

2

I've been reading Diaz's book Pro JavaScript Design Patterns. Great book. I myself am not a pro by any means. My question: can I have a static function that has access to private instance variables? My program has a bunch of devices, and an output of one can be connected to the input of another. This information is stored in the inputs and outputs arrays. Here's my code:

var Device = function(newName) {
    var name = newName;
    var inputs  = new Array();
    var outputs = new Array();
    this.getName() {
        return name;
    }
};
Device.connect = function(outputDevice, inputDevice) {
    outputDevice.outputs.push(inputDevice);
    inputDevice.inputs.push(outputDevice);
};

//implementation
var a = new Device('a');
var b = new Device('b');
Device.connect(a, b);

This doesn't seem to work because Device.connect doesn't have access to the devices outputs and inputs arrays. Is there a way to get to them without adding privledged methods (like pushToOutputs) to Device that would expose it?

Thanks! Steve.

+1  A: 

You're creating a closure, and there's no way to access closure variables from outside except by using a privileged method.

Frankly, I never felt a need for private variables, especially in Javascript code. So I wouldn't bother and make them public, but that's my opinion.

Eugene Morozov
+2  A: 

Eugene Morozov is right - you can't access those variables if you create them in the function as you are. My usual approach here is to make them variables of this, but name them so it's clear they're meant to be private:

var Device = function(newName) {
    this._name = newName;
    this._inputs  = new Array();
    this._outputs = new Array();
    this.getName() {
        return this._name;
    }
};
Device.connect = function(outputDevice, inputDevice) {
    outputDevice._outputs.push(inputDevice);
    inputDevice._inputs.push(outputDevice);
};

//implementation
var a = new Device('a');
var b = new Device('b');
Device.connect(a, b);
Jesse Rusak