0

这就是我的问题,这些天很酷的孩子们是如何布置他们的 javascript 的?我一直在环顾四周,据我所知,每个人似乎都在做不同的事情,有些人将他们的函数包含在对象文字中,有些人似乎只是列出了函数并在上面列出了所有变量。那么每个人都认为我应该如何布置我的代码。

var logsomestuff ="somestuff";

function logIt(){ 
   console.log(logsomestuff);
}

或者可能

logIt = {
   logsomestuff: "somestuff",
   logIt: function(){
      console.log(this.logsomestuff);  
   }
}

我不知道人们怎么想,最好的方式来布局你的 js?以上只是两个例子,我相信还有很多。谢谢你的帮助

4

2 回答 2

3

所有很酷的孩子都在使用函数闭包来限定他们的变量。

这段代码立即执行,并且在全局范围内没有任何内容,一切都挂在 jQuery $.app 变量上。

(function($) {

  $.app = $.app || {};

  $.app = { 
      log : function(stuff) {
        console.log(stuff);
      },
      helpers : { 
          convertJsonDateString = function(date) {
               return "somecrazyregex";
          }
      };

})(jQuery);
于 2012-08-21T19:06:04.013 回答
1

Closure is by far the "cool" kids way of doing things these days, for the reasons Dave mentioned and also because it actually allows Javascript to have some structure. The way I set my modules up is typically like this:

var ModuleName = function(sandbox, options) {

    //Class functions
    function someButtonHandlerOrSomething() {

    }

    return {
        init: function() { //Initialization logic }
        load: function() { //Load }
        destroy: function() //On exit }
    }
}

I also use a core function to abstract libraries such as jQuery so my application is not dependent which admittedly forces me to write a lot of vanilla Javascript, but I actually prefer it that way.

This video helped me a lot: http://www.youtube.com/watch?v=vXjVFPosQHw

于 2012-08-21T19:49:28.523 回答