[英]Why does jslint say my variable is out of scope?
Why does jslint say that id_interval is out of scope? jslint为什么说id_interval超出范围? JavaScript is function scoped last time I checked.
我上次检查JavaScript的功能范围。
Pub.elementLoaded = function (id, callback) {
var isLoaded = document.getElementById(id);
var id_interval = setInterval( function() {
if (isLoaded) {
callback();
clearInterval(id_interval);
}
}, 1);
};
JSLint enforces what its author considers best practices, not the actual JavaScript syntactic rules. JSLint执行其作者认为的最佳实践,而不是实际的JavaScript语法规则。 Quoting from jslint.com about variable declarations:
从jslint.com引用有关变量声明的信息:
JSLint uses the intersection of the var rules and the let rules, and by doing so avoids the errors related to either.
JSLint使用var规则和let规则的交集,从而避免了与这两个规则有关的错误。 A name should be declared only once in a function.
名称只能在函数中声明一次。 It should be declared before it is used.
应该在使用它之前声明它。
In your code, id_interval
is used inside its own declaration, at which point it strictly isn't declared yet. 在您的代码中,
id_interval
在其自己的声明中使用,在这一点上,尚未严格声明它。
A late answer for others like me who arrive here with the same question: as @GertG explains, JSLint just wants you to declare the variable before the block in which you use it. 对于像我一样到达这里的其他人,我也有一个同样的问题:如@GertG所述,JSLint只希望您在使用它的块之前声明该变量。
You have to add var id_interval;
您必须添加
var id_interval;
before you use the setInterval()
, and then remove var
on the following line, because now you've already declared it: 在使用
setInterval()
,然后在下一行删除var
,因为现在您已经声明了它:
Pub.elementLoaded = function (id, callback) {
var isLoaded = document.getElementById(id);
var id_interval;
id_interval = setInterval( function() {
if (isLoaded) {
callback();
clearInterval(id_interval);
}
}, 1);
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.