【问题标题】:What are all the possible places a ReferenceError can be thrown?可以抛出 ReferenceError 的所有可能位置是什么?
【发布时间】:2013-10-12 01:53:37
【问题描述】:

给定一个已定义的全局变量exists 和一个变量notexists,什么是ReferenceErrors 被抛出和不被抛出的详尽列表?到目前为止,我同意:

notexists;
notexists++;

还对不被抛出的特殊情况感到好奇,例如:

var notexists = notexists; //equivalent to: var notexists; notexists = notexists;
typeof notexists; //special case?

我还有什么遗漏吗?

理由:我正在编写一个静态分析器,我必须完美地涵盖所有这些情况。

【问题讨论】:

  • 看看JSHint是怎么做的?

标签: javascript semantics referenceerror


【解决方案1】:

编辑此答案以制作详尽的列表。

是的:

notexists;
notexists++;
notexists.whatever;
void notexists;
notexists();

没有:

notexists = exists;
var notexists = notexists;
typeof notexists;
delete notexists;

【讨论】:

  • 在 undefined 上使用属性访问器总是会抛出一个引用错误。这与使用的运算符无关。 e.g., delete notexists vs delete notexists.whatever
  • @DanHeberden:实际上,delete notexists 可以正常工作,但delete notexists.whatever 会抛出ReferenceError
  • 我认为“是”列表不会很有用,而且它往往会变得非常大。 “否”列表应该基本上由typeof notexistsdelete notexists 组成。其他情况不同,第一种是吊装,最后一种是物业访问。您是否根据规范中的产品解析代码?如果您仔细阅读规范,您会发现抛出该错误的情况并不多。此外,您还必须考虑范围链和提升。
  • @bfavaretto:我正在使用 mozilla-parser-api 样式的解析器。这个问题的原因是我正在编写一个代码转换器,以便所有未绑定的变量foo 引用$GLOBAL.foo。我有一些陷阱,而不是ReferenceError,我得到的是undefined。一旦我通过将foo 转换为$GLOBAL.get_var('foo') 来解决此问题,如果foo 不存在,则会抛出ReferenceError,然后typeof notexists 在不应该存在时开始失败。所以这就是我正在寻找的那种列表..
  • @Claudiu 这正是我的观点“在 undefined 上使用属性访问器总是会引发引用错误”。 delete notexsists.whatever 使用引用运算符惊喜
猜你喜欢
  • 1970-01-01
  • 2011-08-22
  • 1970-01-01
  • 1970-01-01
  • 2010-11-26
  • 1970-01-01
  • 2014-07-31
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多