在Javascript中访问私有实例变量的静态公共方法

时间:2009-03-16 11:07:47

标签: javascript oop static closures

我一直在读Diaz的书Pro JavaScript Design Patterns。好书。无论如何,我自己都不是职业选手。我的问题:我可以拥有一个可以访问私有实例变量的静态函数吗?我的程序有很多设备,一个输出可以连接到另一个设备的输入。此信息存储在输入和输出数组中。这是我的代码:

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);  

这似乎不起作用,因为Device.connect无法访问设备输出和输入数组。有没有办法在没有向Device公开的方法(例如pushToOutputs)的情况下将它们暴露给它们?

谢谢! 史蒂夫。

2 个答案:

答案 0 :(得分:2)

Eugene Morozov是对的 - 如果您在函数中创建它们,则无法访问这些变量。我通常的做法是将它们变为this的变量,但是将它们命名为明确它们是私有的:

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);

答案 1 :(得分:1)

您正在创建一个闭包,除非使用特权方法,否则无法从外部访问闭包变量。

坦率地说,我从未觉得需要私有变量,特别是在Javascript代码中。所以我不打算把它们公之于众,但那是我的看法。