TE
科技回声
首页24小时热榜最新最佳问答展示工作
GitHubTwitter
首页

科技回声

基于 Next.js 构建的科技新闻平台,提供全球科技新闻和讨论内容。

GitHubTwitter

首页

首页最新最佳问答展示工作

资源链接

HackerNews API原版 HackerNewsNext.js

© 2025 科技回声. 版权所有。

Ask HN: Javascript best practices?

51 点作者 mattiss超过 15 年前
How much does it make sense to decompose your javascript routines into separate files? Do you have .js for related classes and methods and one page wide .js to call everything else?<p>EDIT: The above was just an example, I'm looking for most things related to JS.

16 条评论

n8agrin超过 15 年前
Always use "var" to define a variable, unless you know exactly what you are doing. e.g.:<p><pre><code> var foo = 'bar'; </code></pre> When you don't use "var" the Javascript interpreter breaks out of the current scope and continues to do so all the way until it hits the final global scope (generally the window object in browsers). If it does not find the variable, it then defines it. If it does find it, it will trample the found variable with the new value. For example:<p><pre><code> var foo = 'bar'; function baz() { foo = 'baz'; } baz(); // now foo == 'baz'; console.log(foo); &#62;&#62;'baz' </code></pre> Google "Javascript var keyword" for more info.<p>EDIT: I'll add that this functionality, which is part of a general language feature known as a "closure", is incredibly powerful when used successfully, but that's out of the scope of my comment.
评论 #836163 未加载
mindviews超过 15 年前
I like to use separate files for organization during development and then merge and minify for deployment. Just make sure you have an automated process because you don't want to make mistakes doing it by hand.
评论 #836103 未加载
thingsilearned超过 15 年前
Many frameworks have some tools for dealing with multiple javascript files. I use django-compress for example and love it.<p>It allows you to have many different javascript files to separate your code logically, and it automatically compresses them into one file for you for deployment. In this way you don't have to compromise speed for clarity.<p>If you're interested in advanced JS I highly recommend this book. <a href="http://jspro.org/" rel="nofollow">http://jspro.org/</a>
评论 #836073 未加载
评论 #836115 未加载
评论 #836041 未加载
rudenoise超过 15 年前
I like Douglas Crockford's opinions and advice on many aspects of JavaScript:<p><a href="http://javascript.crockford.com/" rel="nofollow">http://javascript.crockford.com/</a><p>Conventions:<p><a href="http://javascript.crockford.com/code.html" rel="nofollow">http://javascript.crockford.com/code.html</a><p>and his book "JavaScript The Good Parts" is well worth a read, even to experiences JS developers<p><a href="http://www.amazon.com/exec/obidos/ASIN/0596517742/wrrrldwideweb" rel="nofollow">http://www.amazon.com/exec/obidos/ASIN/0596517742/wrrrldwide...</a>
irrelative超过 15 年前
Just my 2 cents: Javascript gives you plenty of rope to hang yourself with. Personally, I try to stay away from prototypical objects unless the style fits very cleanly with what I'm trying to do. Otherwise,the best way I've found to keep my sanity is to pick whatever language you're developing the backend with, and use as many conventions you've established there as possible.<p>For me, this means my Javascript looks more like Python -- it can be a little weird, but switching between the frontend and the backend is easier that way.<p>I'd also recommend using objects as namespaces if you're not dealing with prototypical objects. It makes grepping easier - you can search for 'Graphs.init' instead of 'init' in this example:<p>var Graphs = {<p><pre><code> state_variable: null, // store global state somehow init: function() { // Some initialization code }, refresh: function(img_element, url) { // some code to refresh the src url }</code></pre> };
taitems超过 15 年前
Just remember that sometimes doing things the "right" way can really slow your code down. I started coding believing that text should be added with createTextNode and any HTML element should be created via createElement.<p>This causes two issues:<p>1. Memory leaks from deleted or hidden DOM that is still referenced.<p>2. Performance. innerHTML is still probably the fastest method of adding elements, as dirty as it seems.
kls超过 15 年前
I tend to create a page controller js file that my html file loads. I do not embed any JavaScript in the page rather, I grab any dom elements that I need via JavaScript so that way there is a clean separation between code and HTML. I tend to prefer Dojo as far as frameworks, so i will use dojo.byId or dijit.byId to grab references to my nodes in my page init function.<p>I intentionally make my controller file procedural and then I have a custom life-cycle event controller that fires off events for page init, reload, load data, page unload, etc.. so my developers can just fill in the blanks. Any data access is done by calling methods on a service facade which again is purposefully procedural. The service facade then calls any server side services we need (we don't do form posts any more, JSON is far more robust for submitting data). Finally, we use Dijit for any of our widget and any of our model / utility / OO needs.<p>I know it's no purely JavaScript best practices, and it is more related to project file layout and architecture, but I find it gives me the best architecture for my team size (100+). It helps me on-board people quickly and graduate their skill set while maintaining clean code and allowing advanced features.<p>I can start a junior on pure html layout, then we can train them to do controller modification, then to work on service facades and then when they have a good foundation in prototype base OO we can graduate them into building reusable widgets and subsystems for the controller and service facade developers. It works well and allows developers to work proficiently at their skill set without mucking up the whole system.<p>As well the service facades make it easy to contract out entire web projects while my internal team builds server side services to support the effort. This allows us to expand our work force, to a larger pool, without having to vet new developers to deep into business rules to get them up and running.
csytan超过 15 年前
I'll assume this is for client side js, since that's what most people use =)<p>Most of the js I write involves jQuery. As such, I find it's very useful to separate reusable components into jQuery plugins in separate files. If you don't use jQuery or another library which allows plugins, then it's best to create your own namespaced module.<p>See the "Module pattern" for more info: <a href="http://www.yuiblog.com/blog/2007/06/12/module-pattern/" rel="nofollow">http://www.yuiblog.com/blog/2007/06/12/module-pattern/</a><p>Depending on the complexity of your code, you might want to look into javascript build systems -- there's at least one for every major web framework.<p>Here's some advantages they offer: - Allow bunding of many js files into one mega js file. (reduces HTTP requests for faster page loading) - Specify javascript dependencies using special syntax. (easier maintenance) - Versioning support (so users don't get an old cached version of your code)<p>When bundling js files, I try to aim for a maximum of two js files per page. One contains code which is global to the whole site (this is cached on subsequent views), and the second which contains page specific code.
gtani超过 15 年前
Big topic, here's things i refer to repeatedly<p><a href="http://yuiblog.com/blog/2008/09/26/oojs/" rel="nofollow">http://yuiblog.com/blog/2008/09/26/oojs/</a><p><a href="http://yuiblog.com/assets/pdf/oojs-ch-8.pdf" rel="nofollow">http://yuiblog.com/assets/pdf/oojs-ch-8.pdf</a><p><a href="http://mashraqi.com/2008/07/high-performance-ajax-applications.html" rel="nofollow">http://mashraqi.com/2008/07/high-performance-ajax-applicatio...</a><p><a href="http://www.smashingmagazine.com/2008/09/16/jquery-examples-and-best-practices/" rel="nofollow">http://www.smashingmagazine.com/2008/09/16/jquery-examples-a...</a><p><a href="http://dev.opera.com/articles/view/the-seven-rules-of-unobtrusive-javascrip/" rel="nofollow">http://dev.opera.com/articles/view/the-seven-rules-of-unobtr...</a><p><a href="http://www.reddit.com/r/programming/comments/7rtxa/has_anyone_else_hated_javascript_but_later/" rel="nofollow">http://www.reddit.com/r/programming/comments/7rtxa/has_anyon...</a><p><a href="http://code.google.com/p/jslibs/wiki/JavascriptTips" rel="nofollow">http://code.google.com/p/jslibs/wiki/JavascriptTips</a>
dan_sim超过 15 年前
3 years ago, I started a blog about javascript called Javascript Kata at <a href="http://www.javascriptkata.com" rel="nofollow">http://www.javascriptkata.com</a> . I will try to write more and more about best practices and new ways of doing things.
whalesalad超过 15 年前
Can anyone elaborate on when one giant JS file (benefit here is of course reducing HTTP requests) becomes too large? Right now I am splitting up JS files in a fairly simple manner: a single site-wide file with common methods and utilities, and then a handful of smaller files for various aspects of the site. I think that they are each small enough to all be combined into one single one... but when is that single file too large?
评论 #836157 未加载
seanlinmt超过 15 年前
I found this quite good for constructing tidy javascript code, <a href="http://ejohn.org/apps/learn/" rel="nofollow">http://ejohn.org/apps/learn/</a><p>I haven't had time to look into this but there's also a project called Doloto to help optimise your javascript, <a href="http://research.microsoft.com/en-us/projects/doloto/" rel="nofollow">http://research.microsoft.com/en-us/projects/doloto/</a>
geuis超过 15 年前
Use ===, !== etc instead of == or !=. They aren't the same
erlanger超过 15 年前
* Comment with JSDoc style<p>* Auto-build docs and script for development and production environemnts (easy to concatenate and then pipe this to YUI Compressor)<p>* Use an MVC project organization or something like-minded. You can't just throw files representing widgets around.<p>* Write unit tests. JSUnit and SrewUnit (I prefer the latter) work well for this.<p>* Format your code nicely (this goes for any code but I find a ton of terribly formatted JS)<p>* Use one common library for any core object prototype changes (on Element, Array, Function, etc.) and don't modify them further.<p>* JSLint code you're unsure about.<p>* The best way to dynamically load code is just to write script tags to the document.<p>A few style-concerned ones...<p>* Don't use the module pattern. It's rarely appropriate, hiding methods does nobody good, just use a closure.<p>* Only create elements when absolutely necessary and destroy ones that you will no longer use. There's no garbage collector in that regard.<p>* Use a routing system to manipulate and read document.location.hash (and the browser history) so that pages have real URLs and navigate like webpages.<p>* Callbacks and delegates are great, they should be used all over the place.<p>* Use events and listeners to connect the parts of your app.
评论 #836445 未加载
评论 #836277 未加载
评论 #836255 未加载
评论 #836527 未加载
ilyak超过 15 年前
When I hear "best practices" I reach for my Giant Spiked Club of Holy Wrath.
评论 #836454 未加载
adrianwaj超过 15 年前
Obfuscate variable and function names with junk words. On Windows, Jasob was easily the best <a href="http://www.jasob.com/" rel="nofollow">http://www.jasob.com/</a> for it (I tried using many others including online offerings). You need to do this if worried about others seeing and using your code, especially competitors.<p>edit: am I stupid? But when you obfuscate, you also radically shorten the length of a JS file, thus making it quicker to download: EG:<p>function c(g){var m=0;while(m&#60;g.length){var r=g[m];r.l=d(r.n,r.o);if(r.j==true){ r.k=e(r.n,r.o,r.l);}else{r.k=0;}r.t=f(r.l+r.k);m++;}}
评论 #836360 未加载