封装在backbone.js中
这可能是一个常见的 javascript 或 jQuery 问题 - 我正在使用backbone.js,我希望在一个类中有一个可供子类使用的私有方法。这可能吗?
var fooView = Backbone.View.extend({
initialize: function () {
this._privateFunc();
},
_privateFunc: function () {
...
}
});
var subFooView = fooView.extend({
initialize: function () {
this.coolFunc();
this._privateFunc();
},
coolFunc: function () {
...
}
});
但此时_privateFunc并没有暴露给外界。我对 javascript 封装还很陌生,所以如果有明显的答案,请原谅我。 :D
This may be a general javascript or jQuery question- I'm using backbone.js and I'd like to have a private method in one class that can be used by subclasses. Is this possible?
var fooView = Backbone.View.extend({
initialize: function () {
this._privateFunc();
},
_privateFunc: function () {
...
}
});
var subFooView = fooView.extend({
initialize: function () {
this.coolFunc();
this._privateFunc();
},
coolFunc: function () {
...
}
});
But then _privateFunc is not exposed to the outside world. I'm pretty new to encapsulation in javascript so forgive me if there's an obvious answer. :D
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果你的意思是真正的私人,你可以尝试这样的事情......
If you mean really private, you may try something like this...
您正在寻找的内容更准确地称为受保护而不是私有可访问性。没有办法在 JavaScript 中直接实现这一点。
您最好的选择可能只是公开
_privateFunc
并使用带有下划线的方法仅供子类使用的约定。您还可以在以下位置实现
__noSuchMethod__
父类,然后检查该方法是否被子类调用并执行受保护的方法。然而,这是一个 Mozilla 扩展。What you're looking for is more accurately called protected rather than private accessibility. There's no way to directly implement this in JavaScript.
Your best bet is probably just to expose
_privateFunc
and use the convention that methods with underscores are only intended to be used by subclasses.You could also implement
__noSuchMethod__
in the parent and then check that the method is being called by a subclass and execute the protected method. However, this is a Mozilla extension.