为什么 class 是 JavaScript 中的保留字?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7524618/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
why is class a reserved word in JavaScript?
提问by wukong
I am planning to implement class inherit interface using JavaScript. class
is the perfect word as the name of the constructor.
我计划使用 JavaScript 实现类继承接口。class
是作为构造函数名称的完美词。
class = function (classname) {}; // create a class with classname
classA = new class("classA"); // create a class named classA
Unfortunately, class
is a reserved word in JavaScript.
不幸的是,class
是 JavaScript 中的保留字。
Why does JavaScript reserve the word class
(since it never uses it)?
为什么 JavaScript 保留这个词class
(因为它从不使用它)?
回答by zzzzBov
It's reserved to future-proof ECMAScript
它保留给面向未来的 ECMAScript
The following words are used as keywords in proposed extensions and are therefore reserved to allow for the possibility of future adoption of those extensions.
以下词在提议的扩展中用作关键字,因此保留以供将来采用这些扩展的可能性。
Don't fret though, if you're using best-practices in your JavaScripts, you're placing all accessible functions/variables/constructors in a namespace, which will allow you to use whatever name you'd like:
不过不要担心,如果您在 JavaScript 中使用最佳实践,您会将所有可访问的函数/变量/构造函数放在一个命名空间中,这将允许您使用任何您喜欢的名称:
foo = {};
foo['class'] = function(){...code...};
var myClass = new foo['class']();
回答by Thilo
Languages evolve. It is prudent to reserve a few keywords that might come in use later. According to the ECMA standard, class
is a Future Reserved Word.
语言在进化。保留一些以后可能会用到的关键字是明智的。根据 ECMA 标准,class
是未来保留字。
If you did not reserve them, introducing new keywords could conflict with existing code (which already might be using the word for other things). Happened with Java and assert
.
如果您没有保留它们,则引入新关键字可能会与现有代码(可能已经将该词用于其他用途)发生冲突。发生在 Java 和assert
.
回答by username.ak
Now it's used in ECMAScript? 2015 Language Specification:
现在它在ECMAScript 中使用了吗?2015 语言规范:
class Foo {
constructor(bar) {
this.bar = bar;
}
}
new Foo(10).bar; // 10
回答by MikeM
class
is reserved as a future keyword by the ECMAScript specification
class
ECMAScript 规范保留作为未来关键字
回答by Sivakumar
It is there so that support can be added in future without breaking existing programs. Please take a look at the following post.
它在那里,以便将来可以在不破坏现有程序的情况下添加支持。请看下面的帖子。
You can also look at
你也可以看看
https://developer.mozilla.org/en/JavaScript/Reference/Reserved_Words
https://developer.mozilla.org/en/JavaScript/Reference/Reserved_Words