JavaScript中的隐私权 [英] Privacy in JavaScript
问题描述
函数作用域提供JavaScript中唯一的隐私。
Function scoping offers the only privacy in JavaScript.
所以规范:
function Ctor(dep1, dep2) {
this._dep1 = dep1;
this._dep2 = dep2;
}
Ctor.prototype.foo = function() {
// use this._dep1/2...
}
...的问题在于它没有为注入的依赖项提供封装。
...is problematic in that it offers no encapsulation for the injected dependencies.
提供真正封装的替代方案(尽管在 foo
的位置方面略有不同)可能是:
An alternative (albeit slightly different in terms of location of foo
) that offers real encapsulation might be:
function factory(dep1, dep2) {
return {
foo: partial(foo, dep1, dep2), // or use bind (partial could be a library fn for partial application)
};
}
function foo(dep1, dep2) {
// use dep1/2
}
但我很少看到这种模式。是否有充分的理由不使用后者?
But I rarely see this pattern. Is there a good reason to not use the latter?
推荐答案
您已经说明了第二种模式的优点。缺点是:
You already state the advantages of the second pattern. The disadvantages are:
-
您必须按可见性对方法进行分组(即使私有方法与公共方法密切相关,但几乎与其他私有方法无关),或重复对象文字中的所有公共方法(这对jsdoc不起作用)。
you must either group methods by visibility (even if the private method is intimately related with a public one, but barely related to other private methods), or repeat all public methods in the object literal (which doesn't work well with jsdoc).
代码介绍一个单独的函数对象,用于你的类的每个实例,这会牺牲一些性能(这通常无关紧要,但有时可能会有所不同)
the code introduces a separate function object for every instance of your class, which sacrifices some performance (this usually doesn't matter, but sometimes might)
与许多私有修饰符不同编程语言,这种封装是无法规避的,即使误用,我真的知道自己在做什么(从历史上看,JavaScript一直是一个环境,任何事情都有,并且许多人将其成功归功于这种可扩展性)
unlike private modifiers in many programming languages, this encapsulation can not be circumvented, even if misapplied and I really know what I am doing (historically, JavaScript has been an environment where anything goes, and many attribute its success to this extensibility)
这篇关于JavaScript中的隐私权的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!