JSLint:超出三元变量集的范围 [英] JSLint: used out of scope for ternary variable set

查看:42
本文介绍了JSLint:超出三元变量集的范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的代码块:

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

JSLint在等号后突出显示 MYAPP,并显示消息 MYAPP已超出范围。

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

这有什么问题?

推荐答案

如果您使用 var ,则您声明一个局部变量。
如果您执行 MYAPP || {} ,那么您通常会尝试为全局变量或先前声明的变量设置默认值。

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.

范围是什么 MYAPP 应该是?如果是全局的,则类似

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 = {};

如果您在脚本的顶层定义了变量(即不在函数中),那是全球性的如果您在两个具有相同名称的不同脚本标记(或javascript文件)中具有全局变量,则它们是相同的变量。
如果要从其他脚本标签(或javascript文件)隐藏变量,请考虑使用IIFE(立即调用的函数表达式)。例如

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.

这篇关于JSLint:超出三元变量集的范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆