在 JavaScript 中从子类调用基类中的私有方法的解决方法
base = function () {
this.A = function () {
this.B();
}
this.B = function () {} // ABSTRACT!
var E = function () {
alert('I am E');
}
}
sub = function () {
this.B = function () {
alert('I am B');
}
this.D = function () {
E();
}
}
sub.prototype = new base();
情况 1:
(new sub()).D();
正如预期的那样,这不起作用,因为 D 和 E 位于不同的闭包中。我想将 E 保持为私有,因为它永远不应该被直接调用(即在实例上)。我明白不允许访问E的原因是为了保证封装性,但是我能做什么呢?我唯一的两个选择似乎是要么使其具有特权(就像我说的,我反对,因为它将允许在实例上调用它)或手动将其复制到我的每个子类中作为私有方法(这不是一个解决方案)。
情况2:
(new sub()).A();
当我解析原型链的更高层时,我是否在下一个函数调用的末尾“重置”/开始?
是的。
base = function () {
this.A = function () {
this.B();
}
this.B = function () {} // ABSTRACT!
var E = function () {
alert('I am E');
}
}
sub = function () {
this.B = function () {
alert('I am B');
}
this.D = function () {
E();
}
}
sub.prototype = new base();
Situation 1:
(new sub()).D();
This doesn't work, as expected, since D and E are in different closures. I want to keep E private, since it should never be invoked directly (i.e. on an instance). I understand the reason for not being allowed to access E is to ensure encapsulation, but what can I do? My only two options appear to be to either make it privileged (which like I said, I am against since it will allow it to be called on an instance) or to manually copy it into each of my subclasses as a private method (which isn't much of a solution).
Situation 2:
(new sub()).A();
When I resolve higher up the prototype chain, do I "reset"/start at the end at the next function call?
Yes.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我已使用以下步骤在 JavaScript 中创建具有私有和公共作用域的类:
function foo() {}; foo._private = true;
)下面是一些代码:
要查看输出,请查看 this代码笔。
要查看稍微清理的代码以使每个表达式的目的更清晰,签出此代码笔。
请注意,
function C() {}
被function Interface() {}
完全封装,但(new Interface()).D()
仍然可以访问它。另请注意,
(new Interface()).A()
调用Subclass#B()
。I have used the following steps to create a class with private and public scope in JavaScript:
function foo() {}; foo._private = true;
)Here's some code:
To see the output, checkout this code pen.
To see it with the code cleaned up a little bit to make the purpose of each expression a little clearer, checkout this code pen.
Note that
function C() {}
is fully encapsulated byfunction Interface() {}
but(new Interface()).D()
still has access to it.Also, note that
(new Interface()).A()
callsSubclass#B()
.