99re热这里只有精品视频,7777色鬼xxxx欧美色妇,国产成人精品一区二三区在线观看,内射爽无广熟女亚洲,精品人妻av一区二区三区

七、JS 推薦寫法

2018-06-17 19:15 更新
  1. 除了三目運算,if,else等禁止簡寫
     // 正確的書寫
     if (true) {
         alert(name);
     }
     console.log(name);
     // 不推薦的書寫
     if (true)
         alert(name);
     console.log(name);
     // 不推薦的書寫
     if (true)
     alert(name);
     console.log(name)
  2. 在需要以{}閉合的代碼段前增加換行,如:for if


     // 沒有換行,小的代碼段無法區(qū)分
     if (wl && wl.length) {
         for (i = 0, l = wl.length; i < l; ++i) {
             p = wl[i];
             type = Y.Lang.type(r[p]);
             if (s.hasOwnProperty(p)) {
                 if (merge && type == 'object') {
                     Y.mix(r[p], s[p]);
                 } else if (ov || !(p in r)) {
                     r[p] = s[p];
                 }
             }
         }
     }
     // 有了換行,邏輯清楚多了
     if (wl && wl.length) {
    
         for (i = 0, l = wl.length; i < l; ++i) {
             p = wl[i];
             type = Y.Lang.type(r[p]);
    
             if (s.hasOwnProperty(p)) {
                 // 處理merge邏輯
                 if (merge && type == 'object') {
                     Y.mix(r[p], s[p]);
                 } else if (ov || !(p in r)) {
                     r[p] = s[p];
                 }
             }
         }
     }
    換行可以是空行,也可以是注釋
  3. 使用Function進行類的定義,不推薦繼承,如需繼承采用成熟的類庫實現(xiàn)繼承


    // 類的實現(xiàn)
     function Person(name) {
         this.name = name;
     }
    
     Person.prototype.sayName = function() {
         alert(this.name);
     };
    
     var me = new Person("Nicholas");
    
     // 將this放到局部變量self
     function Persion(name, sex) {
         var self = this;
    
         self.name = name;
         self.sex = sex; 
     }
    平時咱們寫代碼,基本都是小程序,真心用不上什么繼承,而且繼承并不是JS的擅長的語言特性,盡量少用。如果非要使用的話,注意一點:


    function A(){
        //...
    }
    function B(){
        //...
    }
    B.prototype = new A(); 
    B.prototype.constructor = B; //原則上,記得把這句話加上
    繼承從原則上來講,別改變他的構造函數(shù),否則這個繼承就顯得很別扭了~
  4. 使用局部變量緩存反復查找的對象(包括但不限于全局變量、dom查詢結果、作用域鏈較深的對象)


    // 緩存對象
    var getComment = function() {
        var dom = $("#common-container"),               // 緩存dom
                    appendTo = $.appendTo,                      // 緩存全局變量
            data = this.json.data;                      // 緩存作用域鏈較深的對象
    }
    
    
    //當需要緩存this時必須使用self變量進行緩存
    // 緩存this
    function Row(name) {
        var self = this;
    
        self.name = name;
        $(".row").click(function() {
            self.getName();
        }); 
    }
     self是一個保留字,不過用它也沒關系。在這里,看個人愛好吧,可以用_this, that, me等這些詞,都行,但是團隊開發(fā)的時候統(tǒng)一下比較好。
  5. 使用eval,采取$.parseJSON
    三個原因:
        有注入風險,尤其是ajax返回數(shù)據
        不方便debug效率低,eval是一個執(zhí)行
        效率很低的函數(shù)
    建議: 使用new Function來代替eval的使用,最好就別用。


以上內容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號