如何隔离我的javascript代码以防止冲突?

时间:2011-08-05 20:47:00

标签: javascript

我一直在写很多javascript函数和事件监听器,我想将它们移动到它们自己的命名空间,隔离的地方,当我连接并用我的其他javascript文件缩小它时不会发生冲突。

我还是javascript的新手,所以这个答案可能有一个简单的解决方案。我首先创建了一个javascript对象:

var MySpecialStuff = {
    init: function(){
        //do everything here
    }
};

然后在我的html中,在我要使用它的页面上,我可以初始化这段代码:

<script>
    MySpecialStuff.init();
</script>

但是init方法开始增长,我需要开始将代码分解成更小的块,但是我仍然坚持语法以及如何设置私有方法/变量并在{{1}内调用它们方法和其他私有方法。我怎么能这样做?

我是朝着正确的方向前进的吗?我/我应该采取哪些其他方式来做这类事情?

4 个答案:

答案 0 :(得分:22)

你朝着正确的方向前进。您可以使用module pattern创建一个包含私有成员和方法的对象:

var foo = function(){
  var bar = ""; //private

  function funk(){
    //private function    
    return "stuff";
  }

  return{
    getBar: function(){
      return bar;
    },
    init: function(){
      alert(funk());
    },
    randomMember: 0 //public member
  }


}();

只有返回块中的内容是公共的,但您可以调用任何私有方法/访问返回块中的任何私有方法。

答案 1 :(得分:0)

感谢约瑟夫与另一个解释这种方法的SO问题联系起来:

  

另一种方法,我认为它比对象文字形式的限制性要小一些:

var MySpecialStuff = new function() {

    var privateFunction = function() {

    };

    this.init = function() {

    };
};

答案 2 :(得分:0)

我喜欢将我的代码进一步细分为更模块化的方法。所以,假设我们有一个页面,其中包含一系列博客文章,一个页面菜单和一个侧边栏。我最终得到了这个:

var blog_controller = {
    init: function(){
      document.getElementById('some_element').addEvent('click', this.handleSomeClick);
      this.applySomePlugin(); 
    },
    applySomePlugin: function () {
      /* do whatever needs to happen */
    },
    handleSomeClick: function () {
      // scope will be element
      this.style.color = 'red';
    }
};
var page_menu_controller = {
    init: function(){
      document.getElementById('some_other_element').addEvent('click', this.handleSomeClick);

    },
    handleSomeClick: function () {
      // scope will be element
      this.style.color = 'blue';
    }
};

......等等。这样可以保持代码按目的组织,有助于保持范围清晰,并允许您重复使用可能经常出现的代码元素(例如,如果您在新博客文章中使用AJAX,则可以再次调用this.applySomePlugin)。

这当然是一个快速而又肮脏的例子,但我希望你明白这个想法

答案 3 :(得分:0)

将您放在init函数中的代码的责任划分为主对象的子对象。

MySpecialStuff = {
    // Variables/constants and everything else that needs to be accessed inside the whole MySpecialStuff object
    init: function(){
        //Do only whats required to be globally initiated.
        this.MainMenu.init(); // Main menu stuff usually is.
    }
};

MySpecialStuff.MainMenu = {
    // Variables / constants that are only important to the MainMenu subobject.
    init: function(){
        //Just the initiation stuff thats related to the MainMenu subobject.
    }
};

MySpecialStuff.SlideShow = {
    // Variables / constants that are only important to the SlideShow subobject. 
    init: function(){
        // Same as for the MainMenu with the difference that nonessential objects can be "fired" when required
    }
};