javascript - Mootools 类中的私有(private)方法

标签 javascript oop mootools

我对在 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/

相关文章:

javascript - 启用按钮时运行 javascript 函数

python,函数是一个对象吗?

python - 面向对象编程基础(python)

javascript - 尝试让 "eraser"与 HTML5 Canvas 和 Vaadin 一起使用,但它只是清除

javascript获取当前页面的html

javascript - 适用于 jQuery 和 Mootools 的不可知 Javascript 框架适配器?

php 的 "setcookie"无法跨浏览器工作?

javascript - Mootools 的图像缩放

javascript - three.js 相机绕 Y 轴的旋转似乎关闭

php - 静态还是非静态?