Javascript:自执行类和公共函数

时间:2013-05-08 13:17:24

标签: javascript

我有很多以下课程:

(function() {
   if (!window.Administration) {
     window.Administration = {};
   }
   window.Administration.Customers = (function() {
      // some code and private methods
      return {
      // public methods
      };
   })();
})();

我听说某处公共方法的这种声明不太好,因为js引擎创建的公共方法实例与从​​代码中调用它们一样多......这是真的吗?

在这种情况下,我如何重构我的代码以解决此类内存泄漏但保留自执行功能?

谢谢

1 个答案:

答案 0 :(得分:0)

如果您只担心隐藏方法,则可以使用此构造:

(function(ns) {

    // default constructor
    ns.Blah = function(v) {
        this.v = v;
        setup.call(this); // invoke private method
    }

    // private method, invoked using .call(this)
    function setup()
    {
        this.w = this.v + 123;
    }

    function myhello()
    {
        return 'w = ' + this.w + ' and v = ' + this.v;
    }

    ns.Blah.prototype = {
        hello: function() {
            return myhello.call(this);
        }
    };

}(window.MYNS = window.MYNS || {});
相关问题