为什么这在严格模式下是非法的?
是的,是的,我知道,严格模式还没有出现,但实际上,我正在为未来做计划……
那么,为什么会这样:
$('#'+ $(this).attr('id').replace('control-', 'legend-')).fadeIn();
……ES5 严格模式不允许?
还是我误解了? JSLint:
Problem at line 516 character 18: Strict violation.
我想知道可以更详细一点吗……?
编辑:
为了避免混淆,这里有更多原始代码:
function displayLegend() {
$('#'+ $(this).attr('id').replace('control-', 'legend-')).fadeIn();
}
Yeah, yeah, I know, strict mode ain't around yet, but really, I'm planning for the future...
So, why is this:
$('#'+ $(this).attr('id').replace('control-', 'legend-')).fadeIn();
... not allowed in ES5 Strict mode?
Or am I misinterpreting? JSLint:
Problem at line 516 character 18: Strict violation.
Could it be a little more verbose, I wonder...?
EDIT:
To avoid confusion, here's more of the original code:
function displayLegend() {
$('#'+ $(this).attr('id').replace('control-', 'legend-')).fadeIn();
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
JSLint 中这段代码的一些试验和错误
告诉我出了什么问题:你正在使用
this
作为参数。将this
es 更改为that
s 不会触发错误。正如规范所述:
正如 John Resig 写入,
正如您所展示的,在函数声明中使用代码行会在 JSLint 中引发错误,而在函数表达式中使用它则不会。看来 JSLint 错误地解析了函数声明,看到了此时仍未定义的
this
,并引发了异常。在这一点上,我想我必须引用Juriy Zaytsev('kangax'):
更新:最后我找到了一个解释。如果您阅读 这个帖子,特别是从消息#1512开始,你会读到
我必须承认他的观点是有道理的:如果你的目标是避免全局命名空间污染,你不应该使用函数声明,而应该使用私有函数内的函数表达式无论如何,命名空间。但我同意上述线程中的其他人的观点,即错误消息应该更明确(并且可能会在遇到函数声明时发出警告)。
Some trial-and-error of this code in JSLint
shows me what's wrong: you're using
this
as a parameter. Changing boththis
es tothat
s doesn't trigger the error.As the specification says:
As John Resig writes,
As you showed, using your line of code inside a function declaration throws an error in JSLint, whereas using it inside a function expression doesn't. It looks like JSLint erroneously parses the function declaration, sees
this
, that's still undefined at that moment, and throws an exception.At this point, I think I have to quote Juriy Zaytsev (‘kangax’):
Update: At last I found an explanation. If you read this thread, especially from message #1512 onwards, you'll read that
I have to admit that he has a valid point here: if your goal is to avoid global namespace pollution, you shouldn't use function declarations, but function expressions inside a private namespace, anyway. But I agree with others in the mentioned thread that the error message should be more explicit (and probably throw a warning on encountering a function declaration).
按照 David Dorward 的说法,我发现了一些通过 JSLint 测试的东西。至于为什么要这么做,这真是太奇怪了。
之前:(参见问题)
之后:
编辑:
我问道格拉斯·克罗克福德:
了规范中所说的内容,只是更加清晰!
Following what David Dorward said, I found something that passes JSLint's test. This is downright strange as to why it's doing that.
Before: (see question)
After:
EDIT:
I asked Douglas Crockford:
This confirms what it says in the spec, except it's much clearer!