将大型公共javascript函数分解为较小的私有函数

时间:2014-12-23 12:05:04

标签: javascript jquery

我有JavaScript类,它具有很难维护的巨大功能。

在开始时再点击时调用2个公共函数。我想在这些公共函数中创建私有函数,然后闯入这些公共方法的一些私有函数范围。

var searchResultView;
var SearchResultView = function () {
    me = this;
    this.init = function () {
        // huge code
    }

    this.Search = function () {
        // huge code
    }
}
jQuery(function () {
    searchResultView = new SearchResultView();
    searchResultView.init();
    searchResultView.Search();
}

实现这一目标的最佳方法是什么。我尝试使用下面的方法,但我认为这个嵌套的功能将无法正常工作。

var searchResultView;

function searchResultView() {
    me = this;
    this.init = function () {
        var declareControls = function () {}
        var addEvents = function () {}
        var fillControls = function () {}
        declareControls();
        addEvents();
        fillControls();
    }
    this.Search = function () {
        var validateAndCreateCriteria = function () {
            if (!validateAandGetLocation()) {
                alert("invalid location");
                return false;
            }
            if (!validateAandGetCategory()) {
                alert("choose search type");
                return false;
            }
            var validateAandGetLocation = function () {}
            var validateAandGetCategory = function () {}
        }
        validateAndCreateCriteria();
    }
}
jQuery(function () {
    searchResultView = new searchResultView();
    searchResultView.init();
});

2 个答案:

答案 0 :(得分:1)

如果我理解正确,你应该具有以下功能:

var foo = (function() {
    var  privateBar = function() {  // private function

    },
    privatefooBar = function() {   // private function

    };
    return {
       publicFoo : function() {     //public function
           /* use privateBar and privatefooBar functions here */
       }
    };
})();

稍后您可以使用

访问publicFoo功能
 foo.publicFoo();

但是您无法直接访问privateBar()privatefooBar()的内部函数,因为它们是私有函数。

<强> Updated Fiddle

答案 1 :(得分:0)

简化功能很简单:

function f(..) {
  // many lines here
  return ret_f;
}

如果相当于

function f {
  function f1(..) {
    // not so many lines here
  }
  function f2(..) {
    // not so many lines here
  }
  var ret_f1 = f1(..);
  var ret_f2 = f2(..);
  // calculate ret_f from ret_f1 and ret_f2
  return ret_f;
}

或者如果您喜欢使用匿名函数的这种风格

function f {
  var f1 = function(..) {
        // not so many lines here
  };
  var f2 = function(..) {
        // not so many lines here
  };
  var ret_f1 = f1(..);
  var ret_f2 = f2(..);
  // calculate ret_f from ret_f1 and ret_f2
  return ret_f;
}

我担心你真正的问题是针对现有代码的,并且是关于提取那些有用的较小函数以及如何将它们组合起来的问题。 为此,需要获得完整的代码并理解它。对于这种QA格式,这可能有点多。