【问题标题】:Writing a comma at the end of the first line of a multi-line variable declaration throws an error in Javascript在多行变量声明的第一行末尾写一个逗号会在 Javascript 中引发错误
【发布时间】:2015-10-18 09:02:02
【问题描述】:

我在我正在开发的应用程序中编写了以下变量声明

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");

如果我不以逗号结束声明的第一行,代码就可以正常工作。

如果我以逗号结束第一行(可能有人认为是正确的),那么我会收到这个奇怪的错误:

Uncaught ReferenceError: $elevationAngleKnob is not defined

你认为是什么问题?

【问题讨论】:

  • 我想不出原因。你能用 HTML 和代码创建一个stack snippet 来演示问题吗?
  • 你能显示更多的代码吗? $elevationAngleKnob 的使用是否与所有这些声明在同一个函数中?
  • 第一行以逗号结尾,运行良好。检查这个jsfiddle.net/passionintellectual/hgse340w
  • 如果您不使用逗号,自动分号插入将在第一行终止您的变量声明。然后你创建一个全局变量的负载。所以不,你的代码不好。请注意错误信息。

标签: javascript jquery frontend variable-declaration web-frontend


【解决方案1】:

我怀疑您试图在与这些变量声明不同的函数中使用$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 声明为局部变量,其他所有内容都是对全局变量的赋值,由逗号运算符分隔。

【讨论】:

  • 是的,这就是问题所在,这是有道理的。我没有注意到这个错误是从另一个函数抛出的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-13
  • 2020-07-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-09-12
相关资源
最近更新 更多