【问题标题】:Static public method accessing private instance variables in Javascript在Javascript中访问私有实例变量的静态公共方法
【发布时间】:2010-10-13 14:14:56
【问题描述】:

我一直在阅读 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)的情况下获取它们?

谢谢! 史蒂夫。

【问题讨论】:

    标签: javascript oop static closures


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-10-08
        • 1970-01-01
        • 1970-01-01
        • 2012-05-29
        • 2011-07-04
        • 2011-02-11
        • 2013-05-03
        相关资源
        最近更新 更多