Mootools类中的私有方法

5

我在使用JavaScript中的面向对象编程方面还比较新,我想知道私有方法的最佳实践是什么。目前,我正在使用mootools创建我的类,并通过在方法名前加下划线来模拟私有方法,以强制自己不要在类外部调用该方法。因此,我的类如下所示:

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

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

这是处理JS私有方法的一种好/标准方式吗?
2个回答

12

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文档。 - aubreyrhodes

2

只要您保持一致,就不会遇到麻烦。

然而,通过闭包在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语言中使用相同的东西是天真的。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接