JSLint: used out of scope for ternary variable set

2019-02-24 06:38发布

问题:

I have a code block like this:

/*global MYAPP: true*/
var MYAPP = MYAPP || {};

JSLint highlights "MYAPP" after equal sign with message "MYAPP used out of scope".

What's wrong with that?

回答1:

If you use var then you are declaring a local variable. If you do MYAPP || {} then you are typically trying to set a default value for a global variable, or for a variable declared earlier.

What is the scope of MYAPP supposed to be? If it is global, then something like

MYAPP = window.MYAPP || {}; 

window. stops it from complaining that it is undefined

If it is not global but declared earlier, then

MYAPP = MYAPP || {};

If it is a new variable local to the function that this line is part of then

var MYAPP = {};

If you have a variable defined at the top level of your script (i.e. not in a function), then it is a global. If you have global variables in two different script tags (or javascript files) with the same name, then they are the same variable. If you want to hide a variable from other script tags (or javascript files), consider using an IIFE (immediately invoked function expression). e.g.

(function() {
    var MYAPP = {};
    //code that uses MYAPP;
})();
//MYAPP is not visible out here, or in other script tags/files.


回答2:

For jshint, jslint, sonarqube, etc. no variables could be used without is explicitly declared with var (let or const).

If you want set them global, you must in first time defined what is the current global keyword because it's window into browser but in other context, maybe it's not that !

So see below how to avoid your warning (JSDoc Comment are not part of solution but explained why is usefull).

/**
 * @fileOverview Starting point for Front-end [Your Project Name]'s JavaScript.
 * @author {@link http://www.lesieur.name/|Bruno Lesieur}
 * @version 1.0.0
 * @module Common
 * @requires {@link external:jQuery}
 */

var window = this,

    /**
     * Container for all function of website.
     * @namespace website
     * @global
     * @type {Object}
     */
    website = window.website || {},

    /**
     * Write less, Do more.
     * @external jQuery
     * @global
     * @see {@link https://jquery.com/|jQuery}
     */
    $ = window.$,

    /**
     * Shortcut for $(window).
     * @global
     * @type {jQuery}
     */
    $window = window.$window || $(window);

/**
 * All components (modules) avaiable on all pages.
 * @namespace components
 * @alias components
 * @type {Object}
 * @memberOf website.
 */
website.components = website.components || {};

So in your example the easy way it's :

var window = this,
    MYAPP = window.MYAPP || {};

or

var global = this,
    MYAPP = global.MYAPP || {};

or

var MYAPP = this.MYAPP || {};