簡體   English   中英

JavaScript中“ typeof $”的含義是什么?

[英]What is meaning of “typeof $” in javascript?

以下源代碼中typedef $的含義是什么。 我已從此鏈接中閱讀。

typeof允許標識符從未被聲明過。 因此,在這方面更安全:

但是這里他們使用if (typeof $ !== 'undefined') ,這里$含義是什么。

我從此鏈接復制了以下代碼

<script type="text/javascript">
  if (typeof horizon.d3_line_chart !== 'undefined') {
    //alert("test1");
    //When first time It give alert means it is defiend 
    horizon.d3_line_chart.init("div[data-chart-type='line_chart']",
      {'auto_resize': true});
  }

  if (typeof $ !== 'undefined') {
    //alert("alert2");
    /*
      We first time we run resource usage, then It will show alert, and date options are not showing. So means first time It hides the date options. Means '$' varaible is defined.
    */
   show_hide_datepickers();
  } else {
    addHorizonLoadEvent(function() {
      show_hide_datepickers();
    });
  }

  function show_hide_datepickers() {
    $("#date_options").change(function(evt) {
        // Enhancing behaviour of selectbox, on 'other' value selected, I don't
        // want to refresh, but show hide the date fields
        if ($(this).find("option:selected").val() == "other"){
          evt.stopPropagation();
          $("#date_from input, #date_to input").val('');
          $("#date_from, #date_to").show();
        } else {
          $("#date_from, #date_to").hide();
        }
    });
    if ($("#date_options").find("option:selected").val() == "other"){
      $("#date_from, #date_to").show();
    } else {
      $("#date_from, #date_to").hide();
    }
  }
</script>

在Javascript中, $只是一個變量名,因此:

if (typeof $ !== 'undefined')

只是檢查以查看$變量是否已經定義。 在使用jQuery的代碼中, $符號通常是jQuery對象的別名,因此此代碼將檢查是否存在jQuery或jQuery是否使用$符號。

您沒有向我們展示addHorizonLoadEvent()代碼,但是邏輯表明它可能負責加載jQuery或了解何時包括jQuery的一組東西完成加載,如果代碼發現加載$任何東西,就可以使用它。尚未完成加載。

在您的情況下,作者只是檢查是否存在某些庫並已加載它們:

  • (typeof $ !== 'undefined') ->使用$的庫(在您的情況下$ JQuery)
  • (typeof horizon.d3_line_chart != 'undefined') ->圖表庫?

如果已加載庫,則可以執行一些代碼;如果未加載庫,則不會崩潰。 如果不存在一個庫,也可以嘗試使用另一個庫。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM