0

I wrote the following variable declarations in an application I'm working on

var $currentPage = $(".js-page") 
        $form = $("#new_location"),
        $body = $("body"),
        $submit = $form.find(".js-submit"),
        $elevationAngleKnob = $(".js-knob-elevation-angle"),
        $sunbathingTimeKnob = $(".js-knob-sunbathing-time"),
        $sunbathingStartKnob = $(".js-knob-sunbathing-start"),
        $sunbathingEndKnob = $(".js-knob-sunbathing-end"),
        $currentTimeKnob = $(".js-knob-current-time"),
        $nearestTimeKnob = $(".js-knob-nearest-time"),
        $editLocationForms = $(".edit_location");

If I don't end the first line of the declaration with a comma the code works just fine.

If I end the first line with a comma( as one might think is correct) then I get this strange error:

Uncaught ReferenceError: $elevationAngleKnob is not defined

What do you think is the problem?

4

1 に答える 1

4

$elevationAngleKnobこれらの変数宣言とは別の関数で使用しようとしていると思われます。最初の行の最後にコンマを置くと、これらの変数はすべてローカル変数になり、別の関数でそれらにアクセスしようとするとエラーが発生します。コンマがない場合、セミコロンの自動挿入により次のように変更されます。

var $currentPage = $(".js-page");
$form = $("#new_location"),
    $body = $("body"),
    $submit = $form.find(".js-submit"),
    $elevationAngleKnob = $(".js-knob-elevation-angle"),
    $sunbathingTimeKnob = $(".js-knob-sunbathing-time"),
    $sunbathingStartKnob = $(".js-knob-sunbathing-start"),
    $sunbathingEndKnob = $(".js-knob-sunbathing-end"),
    $currentTimeKnob = $(".js-knob-current-time"),
    $nearestTimeKnob = $(".js-knob-nearest-time"),
    $editLocationForms = $(".edit_location");

これはローカル変数として宣言$currentPageされ、他のすべてはコンマ演算子で区切られたグローバル変数への代入です。

于 2015-07-28T00:41:26.963 に答える