[英]how can i solve ESLint error that 'no-unused-var' with google map
[英]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.