问题
The following code is valid in ESLint with Google's style guide with one exception; the closure function Counter gets a no-unused-vars error when the script is checked using ESLint.
/**
* 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;
}
I would like to have this function (or one structure the same way) as a standalone script that I can include in my HTML and then call from a different script like so:
var count = Counter()
.val(5);
count.incr()
console.log(count.val()) // prints => 6
I have tried including /* exported Counter */ at the top of the script but the error persists. How do I silence/fix this error?
回答1:
Explicitly adding Counter to the global scope silences this error and prevents errors that may occur as a result of the implicit global scope used in the question.
/**
* 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;
};
回答2:
Here's some options for telling the linter to allow a global Counter variable:
Option #1: Add this comment to the top of the js file when you need to use the global variable:
/* globals Counter */
Option #2: Add the variable name to the globals property in your eslint configuration file:
// eslintrc.js
module.exports = {
// ...
globals: {
'Counter': true
}
}
See ESLint documentation here for more info.
Note: you can also use the env property in your config file for predefined sets of globals like: browser (ie. localStorage), jquery, node, etc.). See here.
来源:https://stackoverflow.com/questions/34209063/how-do-you-expose-a-global-javascript-function-without-eslint-no-unused-var-erro