繁体   English   中英

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

[英]Static public method accessing private instance variables in Javascript

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

谢谢! 史蒂夫。

尤金·莫罗佐夫(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);

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

坦白地说,我从没有感到需要私有变量,尤其是在Javascript代码中。 所以我不会打扰他们,也不会将它们公开。但这是我的看法。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM