为什么 JavaScript 保留 Java 关键字?
如您所知,JavaScript 保留了所有 Java 关键字。有谁知道为什么? JavaScript 不鼓励使用这些 Java 关键字,但它们在用作标识符时似乎工作正常。
As you know, JavaScript has all Java keywords reserved. Does anyone know why? JavaScript discourages using these Java keywords, but they appear to work fine when used as identifiers.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
故事是这样的,当他们开发 JavaScript 时(我相信最初称为 Oak(显然,我把这些语言混淆了,之前关于它的原始名称的说法是不正确的。)),Netscape 与 Sun 合作开发了它。为了吸引 Java 社区,他们想让 JavaScript 像 Java 一样,这样 Java 开发人员会感觉更舒服,这就是它们如此相似的原因。
关于设计一种语言,您必须记住的是,您实际上只能一次定义关键字,而不会让该语言的新版本破坏现有代码。在开始时保留一个单词而不使用它比稍后尝试保留它要容易得多。对于像 JavaScript 这样的东西尤其如此,开发脚本的人无法控制它将在哪个浏览器中运行(我现在知道这种情况发生了,但情况可能会更糟)。你能想象一下,如果发现新浏览器采用的下一个版本的 JavaScript 突然无法运行你的应用程序,因为他们保留了一个新的关键字,那该有多疯狂?
The story is that when they were developing JavaScript (originally called Oak I believe (apparently, I got the languages mixed up the previous statement about it's original name is incorrect.)), Netscape partnered with Sun to develop it. To entice the Java community, they wanted to make JavaScript like Java, so that Java developers would feel more comfortable with it, and that is the reason why they are so similar.
What you have to remember about designing a language is that you really only get one shot at defining keywords, without having a new version of the language break existing code. It's much easier to reserve a word at the beginning and not use it than try and reserve it later. This is especially true for things like JavaScript where the person developing the script has no control over which browser it's going to run in (this happens now i know, but it could be a lot worse). Could you imagine how madding it would be to find out that the next version of JavaScript which is adopted by the new browser suddenly won't run your application, because they reserved a new keyword?
好吧,它实际上并不是 Java 关键字,因为 Javascript 除了借用了这个名字之外,与 Java 没有任何关系。
这些名称被保留,以备将来语言扩展时需要。来自 ECMAScript 语言规范:
Well, it's not actually Java keywords, as Javascript doesn't have anything to do with Java except borrowing the name.
The names were reserved in case they would be needed in future expansions of the language. From the ECMAScript Language Specification:
可能是为了避免使用这些关键字作为变量名可能导致的潜在混乱。
我的意思是,想象一下 Java 开发人员试图找出一段带有名为
public
的变量或函数的 JavaScript 代码。即使这是可能的,为了清楚起见,我也建议不要这样做。
Probably to avoid potential confusion that using these keywords as variable names could cause.
I mean, just imagine a Java developer trying to figure out a piece of JavaScript code with a variable or a function named
public
.Even when that is possible, I'd advise against it, for the sake of clarity.
据推测,JavaScript 的开发人员认为这些词可能会在 JavaScript 的未来版本中用于附加功能。为了防止向后兼容性问题,这些词被预先标记为保留。
Presumably the developers of JavaScript assumed that these words may be used for additional functionality in a future release of JavaScript. To prevent backwards-compatibility issues, these words were preemptively marked as reserved.