2011-11-11 34 views
3

在Javascript中有各种reserved words,不能在Identifiers内部使用;其中一些实际上留作将来使用。为了澄清一点,IdentifierIdentifier Name,但不是保留字。标识符名称的确切语法在这里不相关。在Javascript中使用保留字

根据the last paragraph here,虽然看起来有些地方可以使用任何Identifier Name,即使它是保留字。文中提到的有效

a.import 
a["import"] 
a = { import: "test" } 

虽然很明显,我认为第二种形式是合法的,我一直认为第一和第三个则没有。

事实上,this resource表示

foo.if 

为无效代码。

Are there some places were reserved words are actually valid?

作为一个动机,我写了一个API哪里会是有意义的传递形式

{ 
    in: foo, 
    out: bar 
} 

的对象,但我不希望强迫用户把周围in支架。

+0

如果“in”和“out”为您的API在语义上最有意义,那么即使用户必须引用它们,也要继续使用它们。 (我假设你的意思是“加引号”,而不是“放上括号”。) – nnnnnn

+0

是的,我的意思是引号 – Andrea

回答

5

这是ECMA-262版本3和5之间的变化(您可以从get here)。

在这两个版本,第7.6节限定标识符作为

Identifier :: 
    IdentifierName but not ReservedWord 

然而,在部分11.2。1,使用点符号属性访问器从

MemberExpression . Identifier 
CallExpression . Identifier 

3版改为

MemberExpression . IdentifierName 
CallExpression . IdentifierName 

5版,即使用保留名称作为存取点确实是法律现在

如果这个改动是仅仅因为限制标识符在语法上是不必要的,因为没有任何的保留字都不能合法地遵循.,或者我不知道这是否也编入各种实现的现行做法。

PS:一些挖后,我发现在mail from Allen Wirfs-Brock以下,项目编辑器5版:

The ES3 grammar does not allow reserved words (such as true and false) to be used as a PropertyName or to the right of the period in a MemberExpression. Your tests verify that most implementations conform to that restriction while FF has a "non-standard" extension that allows reserved words (or at least the ones you tested) to be used in those contexts.

ES3.1 intentionally adopted the FF extension as a standard part of the language, so when the other implementation are eventually updated to support ES3.1 they should no long report errors for your test cases.

注意的ECMAScript 3.1是什么现在被称为的ECMAScript 5原来的名字。

+0

谢谢,这正是我需要的! :-) – Andrea

1

虽然大多数浏览器不会在a.import处引发错误,但这并不严格合法。如果你想使用保留字,你必须引用它。

访问http://wwwjslint.com,并粘贴以下代码:

var d = { 
    'in': 1 
}; 

此代码是有效的。当你删除引号,但是,会产生一个错误:

Problem at line 2 character 5: Expected an identifier and instead saw 'in' (a reserved word).

+0

这并不能真正回答我的问题。是的,jslint抱怨,但我不确定克罗克福德得到了这个权利。当然我知道每个字符串都可以用引号作为属性名称。但我想知道为什么MDN的人声称报价可以省略。我正在寻找更多的链接到规范的相关部分,我找不到自己。 – Andrea

+0

@Andrea召唤JavaScript控制台,并输入'var d = {a:1}'。结果是“{a:1}”。当你输入'{import:1}'时,显示如下错误:'SyntaxError:import是一个保留的标识符'。 (Firefox 7.0.1)。有关此问题发生的“真实”示例,请参阅:http://userscripts.org/topics/77990。开发者不知道保留字,并且遇到麻烦。 –

+0

@RobW - 'var d = {import:1};'不会为我抛出错误。 –

1

的MDN文章援引的ECMAScript 5规范,该规范火狐符合,但并不是所有的浏览器都符合它以这种方式,即所有的浏览器都没有Ecmascript 5兼容。

1

如果没有引用,你不能依赖它们在所有浏览器/实现上工作。

我会尝试将它们更改为“输入”和“输出”,如果这是有道理的。您必须添加到有关“in”需要引号的文档中的额外句子可能不值得拥有“完美”标识符名称的好处。