Mootools类中的私有方法

aub*_*des 5 javascript oop mootools

我在Javascript中使用oop相对较新,我想知道私有方法的最佳实践是什么.现在,我正在使用mootools来创建我的类,我通过在前面添加下划线来强制私有方法,并强迫自己不要在类之外调用该方法.所以我的班级看起来像:

var Notifier = new Class(
{
   ...
   showMessage: function(message) { // public method
      ...
   },

   _setElementClass: function(class) { // private method
      ...
  }
});
Run Code Online (Sandbox Code Playgroud)

这是在JS中处理私有方法的好/标准方法吗?

Anu*_*rag 12

MooTools提供了一个protect函数方法,因此你可以在任何你想要保护的方法上调用protect来防止被调用Class.所以你可以这样做:

?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.
Run Code Online (Sandbox Code Playgroud)

这不是classJavaScript中未来的保留关键字,您的代码在使用时可能会中断.在这一点上肯定会破坏Safari,但是其他浏览器中的行为也不能得到保证,因此最好不要将其class用作标识符.

使用protect过度创建闭包的一个优点是,如果扩展此类,您仍然可以访问子类中的受保护方法.

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.
Run Code Online (Sandbox Code Playgroud)

如果你想_在方法之前或之后使用命名约定,例如前缀或后缀,那么这也很好.或者您也可以将其_与受保护的方法结合使用.