我对在 Javascript 中使用 oop 比较陌生,我想知道私有(private)方法的最佳实践是什么。现在,我正在使用 mootools 创建我的类,并通过在私有(private)方法前加上下划线并强制自己不要在类外部调用该方法来模拟私有(private)方法。所以我的课看起来像:
var Notifier = new Class(
{
...
showMessage: function(message) { // public method
...
},
_setElementClass: function(class) { // private method
...
}
});
这是在 JS 中处理私有(private)方法的良好/标准方式吗?
最佳答案
MooTools 提供了一个 protect
函数上的方法,因此您可以对任何要防止在 Class
外部调用的方法调用 protect。所以你可以这样做:
var Notifier = new Class({
showMessage: function(message) {
},
setElementClass: function(klass) {
}.protect()
});
var notifier = new Notifier();
notifier.showMessage();
notifier.setElementClass();
> Uncaught Error: The method "setElementClass" cannot be called.
并不是说 class
是 JavaScript 中 future 的保留关键字,您的代码在使用它时可能会中断。此时它在 Safari 上肯定会中断,但也不能保证在其他浏览器中的行为,因此最好不要使用 class
作为标识符。
与自己创建闭包相比,使用 protect
的一个优点是,如果您扩展此类,您仍然可以访问子类中的 protected 方法。
Notifier.Email = new Class({
Extends: Notifier,
sendEmail: function(recipient, message) {
// can call the protected method from inside the extended class
this.setElementClass('someClass');
}
});
var emailNotifier = new Notifier.Email();
emailNotifier.sendEmail("a", "b");
emailNotofier.setElementClass("someClass");
> Uncaught Error: The method "setElementClass" cannot be called.
如果您想在方法之前或之后使用命名约定,例如前缀或后缀 _
,那也完全没问题。或者您也可以将 _
与 protected 方法结合起来。
关于javascript - Mootools 类中的私有(private)方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3229106/