gpt4 book ai didi

带有私有(private)变量的 JavaScript 构造函数模式

转载 作者:行者123 更新时间:2023-11-28 19:36:00 24 4
gpt4 key购买 nike

我知道可以在 JS 中模仿私有(private)变量:

function ConstructorPattern() {
var privateVar = 'hi there';

this.getVar = function() {
return privateVar;
};
};

但是根据Learning JavaScript Design Patterns当引用类 Car 的一些类似代码时和方法toString :

The above is a simple version of the constructor pattern but it does suffer from some problems. One is that it makes inheritance difficult and the other is that functions such as toString() are redefined for each of the new objects created using the Car constructor. This isn't very optimal as the function should ideally be shared between all of the instances of the Car type.

所以在我的例子中给出的解决方案是通过原型(prototype)添加 getVar 函数:

ConstructorPattern.prototype.getVar = function() {
return privateVar;
};

但是这个函数当然不知道 privateVar 是什么。是这样,它不起作用。我知道 module pattern但我特别希望能够实例化多个实例。

有没有办法在原型(prototype)中“正确”使用构造函数模式,同时仍然获得“私有(private)”功能?

编辑:如果没有办法实现这一点,那么为每个类实例重新定义方法真的那么糟糕吗?我最近开始研究采用这种方法的代码库。看来我唯一错过的就是继承?

编辑2:根据已接受答案中的链接标记为重复项。

最佳答案

Is there any way to use the constructor pattern "properly" with prototypes while still getting "private" functionality?

没有。这种具有特权函数的模式基于闭包范围,并且不能与共享函数一起使用。所有特权方法必须是特定于实例的。

If there isn't a way to accomplish this, is it really that bad for methods to be redefined for each class instance?

没有。现代 JavaScript 引擎很好地优化了这种模式。当然,有a little overhead但在典型设置中您不会注意到。

It seems like the only thing I'm missing out on is inheritance?

继承仍然是可能的,请参阅Define Private field Members and Inheritance in JAVASCRIPT module pattern 。当然,派生子类不能直接访问在父构造函数中声明的私有(private)变量,但通常它们也不需要这样做。

关于带有私有(private)变量的 JavaScript 构造函数模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25875793/

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