带有条件的jQuery init函数

时间:2017-12-12 11:12:33

标签: jquery initialization init

我是脚本方面的新手,需要你的帮助来编写更好的代码。我正在使用init函数,它是所有函数的集合,但是现在似乎很少有函数,如果某些条件为真,我想要执行。

示例脚本

 $(document).ready(function() {

var app = {
init: function(){

  // Variable to check condition
  var abc = 0;

  // Default functions
  this.Function1();
  this.Function2();
  this.Function3(); // abc variable will change to 1 if condition is true

  // Conditional functions
  if ( abc === 1 ) {
     this.ConditionFunction1();
     this.ConditionFunction2();
  },

  Function1: function(){ // some Code },
  Function2: function(){ // some Code },
  Function3: function(){
                if(true) { abc == 1; } 
  },
  ConditionFunction1: function(){ // some Code },
  ConditionFunction2: function(){ // some Code }

}
app.init();
});

1 个答案:

答案 0 :(得分:1)

通过重写和定位代码,你可以这样写:

    $(document).ready(function () {

    var app = {
        init: function () {

            // Variable to check condition
            var abc = 0;
            var Function1 = function () { // some Code
                console.log("Function1")
            }

            Function2 = function () { // some Code
                console.log("Function2")

            }

            Function3 = function () {
                if (true) {
                    console.log("Function3")
                    abc == 1;
                }
            }

            ConditionFunction1 = function () { // some Code
                console.log("ConditionFunction1")
            }

            ConditionFunction2 = function () { // some Code
                console.log("ConditionFunction2")
            }
            // Default functions
            Function1();
            Function2();
            Function3(); // abc variable will change to 1 if condition is true

            // Conditional functions
            if (abc === 1) {
                ConditionFunction1();
                ConditionFunction2();
            }
        }
    }
    app.init();
});