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.
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: