1

我一直在阅读 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 无权访问设备输出和输入数组。有没有办法在不向设备添加会暴露它的特权方法(如 pushToOutputs)的情况下获取它们?

谢谢!史蒂夫。

4

2 回答 2

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);
于 2009-03-16T11:42:13.643 回答
1

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

坦率地说,我从来没有觉得需要私有变量,尤其是在 Javascript 代码中。所以我不会打扰并将它们公开,但这是我的意见。

于 2009-03-16T11:34:54.787 回答