簡體   English   中英

如何在沒有ESLint no-unused-var錯誤的情況下公開全局javascript函數?

[英]How do you expose a global javascript function without ESLint no-unused-var error?

以下代碼在ESLint中與Google的樣式指南一起使用,但有一個例外; 使用ESLint檢查腳本時,閉包函數Counter獲取no-unused-vars錯誤。

/**
 * Create a counter that is incremented and returned when called
 * @return {object} - incrementor function
 */
function Counter() {
  var _i = 0;

  /**
   * increment counter
   * @return {int} - The incremented integer
   */
  function _incrementor() {
    _i++;
    return _i;
  }

  _incrementor.incr = function() {
    this.call();
    return _incrementor;
  };

  _incrementor.val = function(val) {
    if (!arguments.length) { return _i; }
    _i = val;
    return _incrementor;
  };

  return _incrementor;
}

我想將這個函數(或一個結構以相同的方式)作為一個獨立的腳本,我可以包含在我的HTML中,然后從不同的腳本調用,如下所示:

var count = Counter()
    .val(5);

count.incr() 
console.log(count.val())  // prints => 6

我已經嘗試在腳本的頂部包含/* exported Counter */但錯誤仍然存​​在。 如何靜音/修復此錯誤?

明確地將Counter添加到全局范圍會使此錯誤無效並防止由於問題中使用的隱式全局范圍而可能發生的錯誤。

 /** * Create a counter that is incremented and returned when called * @return {object} - incrementor function */ this.Counter = function() { var _i = 0; /** * increment counter * @return {int} - The incremented integer */ function _incrementor() { _i++; return _i; } _incrementor.incr = function() { this.call(); return _incrementor; }; _incrementor.val = function(val) { if (!arguments.length) { return _i; } _i = val; return _incrementor; }; return _incrementor; }; 

這里有一些選項可以告訴linter允許全局Counter變量:

選項#1 :當您需要使用全局變量時,將此注釋添加到js文件的頂部:

/* globals Counter */

選項#2:將變量名稱添加到eslint配置文件中的globals屬性:

// eslintrc.js

module.exports = {
  // ...

  globals: {
    'Counter': true
  }
}

有關詳細信息,請參閱此處的ESLint文檔

注意:您還可以在配置文件中使用env屬性來預定義的全局變量集,例如:browser(即localStorage),jquery,node等)。 看到 這里

暫無
暫無

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

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