gpt4 book ai didi

javascript - 在 Javascript 中访问私有(private)实例变量的静态公共(public)方法

转载 作者:行者123 更新时间:2023-11-30 13:43:50 25 4
gpt4 key购买 nike

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

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 的变量,但是给它们命名以便很明显它们是私有(private)的:

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 - 在 Javascript 中访问私有(private)实例变量的静态公共(public)方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/649978/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com