服务器端 Javascript 最佳实践?
我们有一个基于 Java 构建的 CMS,它有用于服务器端 JS 的 Mozilla Rhino。目前 JS 代码库很小,但正在不断增长。在为时已晚和代码变得一团糟之前,我想介绍一些最佳实践和编码风格。
显然,名称空间控制非常重要。但是其他最佳实践怎么样——尤其是对于 Java 程序员来说?
We have a CMS built on Java and it has Mozilla Rhino for the server side JS. At the moment the JS code base is small but growing. Before it is too late and code has become a horrible mess I want to introduce some best practices and coding style.
Obviously the name space control is pretty important. But how about other best practices - especially for Java programmers?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
以下是来自前线的一些提示:
var myns = myns || {};
)Here's some tips from the front lines:
var myns = myns || {};
)正如 Douglas Crockford 喜欢说的那样,JavaScript 是世界上最容易被误解的编程语言。尽管很多人不知道,但有一种正确的 JavaScript 编码方法。我毫不怀疑,如果您让 Java 开发人员在了解如何编写优秀的 JavaScript 之前就开始编码,您将遇到严重的麻烦。
首先要做的就是确保每个人都阅读了 Mozilla 的优秀文章《JavaScript 重新介绍》(https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript)。 JavaScript 最大的问题之一是有很多方法可以完成最常见的任务,本文应该让人们达成共识。另一个重要的参考文献是 Douglas Crockford 的著作,包括 JavaScript:The Good Parts。
另一件让很多 Java/C++ 程序员感兴趣的事情是 JavaScript 使用函数作用域而不是块作用域。这可能会导致一些非常棘手的问题。 A List Apart 上有一篇关于这个问题的很棒的文章,名为 Binding in JavaScript。
To summarize the major issues talked about in the above resources, the most crucial differences to learn are
As Douglas Crockford likes to say, JavaScript is the worlds most misunderstood programming language. Though many people don't know it, there is a right way to code in JavaScript. I have no doubt that if you let Java developers start coding before understanding how to write good JavaScript you will run into serious trouble.
The first thing to do would be to make sure everyone has read Mozilla's excellent article, A re-introduction to JavaScript (https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript). One of the biggest problems with JavaScript is that there are many ways to do most common tasks, and this article should get people on the same page. Another essential reference is Douglas Crockford's work, including JavaScript: The Good Parts.
One other thing that gets a lot of Java/C++ programmers is that JavaScript uses function scope NOT block scope. This can cause some very tricky problems. There's a great article about this issue at A List Apart called Binding in JavaScript.
To summarize the major issues talked about in the above resources, the most crucial differences to learn are
既然您有 Java 中的 JS 引擎,请养成为 JS 代码编写单元测试的习惯。选择一种编码风格并大力应用。如果可能,使用工具检查代码是否符合编码风格。
Since you have a JS engine in Java, make it a habit to write unit tests for your JS code. Select a coding style and apply it vigorously. If possible, use tools to check that the code submits to the coding style.