【问题标题】:Private Methods in a Mootools ClassMootools 类中的私有方法
【发布时间】:2010-07-12 23:59:37
【问题描述】:

我对在 Javascript 中使用 oop 比较陌生,我想知道私有方法的最佳实践是什么。现在,我正在使用 mootools 创建我的类,并且通过在私有方法前加上下划线来模拟私有方法,并强迫自己不要在类外调用该方法。所以我的课看起来像:

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

   _setElementClass: function(class) { // private method
      ...
  }
});

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

【问题讨论】:

    标签: javascript oop mootools


    【解决方案1】:

    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 中未来的保留关键字,您的代码在使用它时可能会中断。此时它在 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.
    

    如果您想在方法之前或之后使用诸如前缀或后缀_ 之类的命名约定,那也很好。或者您也可以将_ 与受保护的方法结合使用。

    【讨论】:

    • 这正是我想要的,非常感谢!下次我必须仔细检查 mootools 文档。
    【解决方案2】:

    嗯,只要你保持一致,你就不会惹上麻烦。

    虽然有一种模式,通过 closure 在 javascript 中创建真正的隐私。

    var Notifier = function() {
    
        // private method
        function setElementClass(class) { 
            //...
        }
    
        // public method
        this.showMessage = function(message) {
            // ...
            setElementClass(...) // makes sense here
        };
    };
    
    var noti = new Notifier();
    noti.showMessage("something");     // runs just fine
    noti.setElementClass("smth else"); // ERROR: there isn't such a method
    

    如果您想添加在所有对象之间继承和共享的公共方法(更小的内存占用),您应该将它们添加到对象的原型中。

    // another way to define public functions
    // only one will be created for the object
    // instances share this function
    // it can also be used by child objects
    // the current instance is accessed via 'this'
    Notifier.prototype.showMessage = function() {
       // ...
       this.otherPublicFunction(...);
    };​
    

    我建议您研究在 javascript 中处理对象的原始方式,因为只有这样您才能知道自己在做什么。像类这样的 Mootools 可以很好地隐藏这种语言与其他语言的不同之处。但事实是,它的差异如此之大,以至于当你在 javascript 中说 class 时认为你做同样的事情是天真的,就像在任何其他基于类的 OO 语言中一样。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-05-23
      • 2022-11-20
      • 1970-01-01
      • 1970-01-01
      • 2020-05-21
      • 2011-12-08
      • 1970-01-01
      相关资源
      最近更新 更多