2012-09-26 37 views
2

我有以下代碼:檢查代碼塊中的變量定義時,爲什麼JSLint的錯誤

  $('#modal .update-title') 
      .change(function() { 
       var title = $('option:selected', this).prop('title'); 
       $(this).prop('title', title); 

       // For the question screen, after the initial set up 
       // changes move the title to the title input field. 
       if ($(this).data('propagate-title') === 'yes') { 
        var m = this.id.match(/^modal_TempRowKey_(\d+)$/); 
        if (m) { 
         $("#modal_Title_" + m[1]).val(title); 
        } 
       } 
      }); 

當我運行的JSLint它給了我下面的錯誤:

Combine this with the previous 'var' statement. 
    var m = this.id.match(/^modal_TempRowKey_(\d+)$/); 

是JSLint的錯還是我我錯了?

+0

塊* *不*在JavaScript中引入一個新的作用域,內部的'var'被「懸掛」。 JSLint告訴你某人(例如Crockford)認爲所有局部變量聲明都應該放在* single *'var'語句中的函數塊的*頂部。 (我不同意任何「風格」指南,也不支持JSLint - 也許可以根據您的指導方針/風格讓JSLint驗證*有效*代碼的選項) – 2012-09-26 03:55:34

+0

(JSLint是*自定義軟件*。將會在一些完全有效的語法結構上出現「錯誤」。使用該工具時請注意:它是*您的*代碼。) – 2012-09-26 04:02:18

+0

@pst - 感謝您的評論。你提到這些塊不會引入新的範圍。這是否適用於在函數中聲明的變量?如果我有一個帶有函數的.js文件,那麼其中的幾個函數是每個變量聲明都被提升到頂部? –

回答

4

使用if條件不會創建新的作用域。所以變量m只有在條件爲真時才存在。所以這裏是你可以做什麼

$('#modal .update-title').change(function() { 
    var title = $('option:selected', this).prop('title'), 
    m = null; // or just m; 
    $(this).prop('title', title); 

    // For the question screen, after the initial set up 
    // changes move the title to the title input field. 
    if ($(this).data('propagate-title') === 'yes') { 
     m = this.id.match(/^modal_TempRowKey_(\d+)$/); 
     if (m) { 
      $("#modal_Title_" + m[1]).val(title); 
     } 
    } 
}); 
+0

雖然這是「爲什麼」,但我不能因爲我反對JSLints(閱讀:Crockfords)這個話題的世界觀而投票。我會*不會*以這種方式修改帖子中的代碼。 JSLint可以解決問題(或配置適當的選項,如果存在)。 – 2012-09-26 04:00:01

相關問題