24个JavaScript初学者最佳实践
- 这里面说到的一个就是使用循环新建一个字符串时,用到了join(),这个比较高效,常常会随着push();
- 绑定某个动作时,可以把要执行的绑定内容定义为一个函数,然后再执行。这样做的好处有很多。第一是可以多次执行,第二是方便调试,第三是方便重构。
As a follow-up to “30 HTML and CSS Best Practices”, this week, we’ll review JavaScript! Once you’ve reviewed the list, be sure to let us know what little tips you’ve come across!
1. Use === Instead of ==
JavaScript utilizes two different kinds of equality operators: === | !== and == | != It is considered best practice to always use the former set when comparing.
“If two operands are of the same type and value, then === produces true and !== produces false.” – JavaScript: The Good Parts
However, when working with == and !=, you’ll run into issues when working with different types. In these cases, they’ll try to coerce the values, unsuccessfully.
2. Eval = Bad
For those unfamiliar, the “eval” function gives us access to JavaScript’s compiler. Essentially, we can execute a string’s result by passing it as a parameter of “eval”.
Not only will this decrease your script’s performance substantially, but it also poses a huge security risk because it grants far too much power to the passed in text. Avoid it!
3. Don’t Use Short-Hand
Technically, you can get away with omitting most curly braces and semi-colons. Most browsers will correctly interpret the following:
if(someVariableExists) x = false
However, consider this:
if(someVariableExists) x = false anotherFunctionCall();
One might think that the code above would be equivalent to:
if(someVariableExists) { x = false; anotherFunctionCall(); }
Unfortunately, he’d be wrong. In reality, it means:
if(someVariableExists) { x = false; } anotherFunctionCall();
As you’ll notice, the indentation mimics the functionality of the curly brace. Needless to say, this is a terrible practice that should be avoided at all costs. The only time that curly braces should be omitted is with one-liners, and even this is a highly debated topic.
if(2 + 2 === 4) return ‘nicely done‘;
Always Consider the Future
What if, at a later date, you need to add more commands to this if statement. In order to do so, you would need to rewrite this block of code. Bottom line – tread with caution when omitting.
4. Utilize JS Lint
14. Use [] Instead of New Array()
The same applies for creating a new array.
Okay
var a = new Array(); a[0] = "Joe"; a[1] = ‘Plumber‘;
Better
var a = [‘Joe‘,‘Plumber‘];
“A common error in JavaScript programs is to use an object when an array is required or an array when an object is required. The rule is simple: when the property names are small sequential integers, you should use an array. Otherwise, use an object.” – Douglas Crockford
15. Long List of Variables? Omit the “Var” Keyword and Use Commas Instead
var someItem = ‘some string‘; var anotherItem = ‘another string‘; var oneMoreItem = ‘one more string‘;
Better
var someItem = ‘some string‘, anotherItem = ‘another string‘, oneMoreItem = ‘one more string‘;
…Should be rather self-explanatory. I doubt there’s any real speed improvements here, but it cleans up your code a bit.
17. Always, Always Use Semicolons
Technically, most browsers will allow you to get away with omitting semi-colons.
var someItem = ‘some string‘ function doSomething() { return ‘something‘ }
Having said that, this is a very bad practice that can potentially lead to much bigger, and harder to find, issues.
Better
var someItem = ‘some string‘; function doSomething() { return ‘something‘; }
18. “For in” Statements
When looping through items in an object, you might find that you’ll also retrieve method functions as well. In order to work around this, always wrap your code in an if statement which filters the information
for(key in object) { if(object.hasOwnProperty(key) { ...then do something... } }
As referenced from JavaScript: The Good Parts, by Douglas Crockford.
19. Use Firebug’s “Timer” Feature to Optimize Your Code
Need a quick and easy way to determine how long an operation takes? Use Firebug’s “timer” feature to log the results.
function TimeTracker(){ console.time("MyTimer"); for(x=5000; x > 0; x--){} console.timeEnd("MyTimer"); }
20. Read, Read, Read…
While I’m a huge fan of web development blogs (like this one!), there really isn’t a substitute for a book when grabbing some lunch, or just before you go to bed. Always keep a web development book on your bedside table. Here are some of my JavaScript favorites.
Read them…multiple times. I still do!
21. Self-Executing Functions
Rather than calling a function, it’s quite simple to make a function run automatically when a page loads, or a parent function is called. Simply wrap your function in parenthesis, and then append an additional set, which essentially calls the function.
(function doSomething() { return { name: ‘jeff‘, lastName: ‘way‘ }; })();
22. Raw JavaScript Can Always Be Quicker Than Using a Library
JavaScript libraries, such as jQuery and Mootools, can save you an enormous amount of time when coding — especially with AJAX operations. Having said that, always keep in mind that a library can never be as fast as raw JavaScript (assuming you code correctly).
jQuery’s “each” method is great for looping, but using a native “for” statement will always be an ounce quicker.
23. Crockford’s JSON.Parse
Although JavaScript 2 should have a built-in JSON parser, as of this writing, we still need to implement our own. Douglas Crockford, the creator of JSON, has already created a parser that you can use. It can be downloaded HERE.
Simply by importing the script, you’ll gain access to a new JSON global object, which can then be used to parse your .json file.
var response = JSON.parse(xhr.responseText); var container = document.getElementById(‘container‘); for(var i = 0, len = response.length; i < len; i++) { container.innerHTML += ‘
- ‘ + response[i].name + ‘ : ‘ + response[i].email + ‘
‘; }
24. Remove “Language”
Years ago, it wasn’t uncommon to find the “language” attribute within script tags.
<script type="text/javascript" language="javascript"> ... </script>
However, this attribute has long since been deprecated; so leave it out.
That’s All, Folks
So there you have it; twenty-four essential tips for beginning JavaScripters. Let me know your quick tips! Thanks for reading. What subject should the third part in this series cover?
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。