1. 使用 === 代替 ==

JavaScript utilizes two different kinds of equality operators: === | !== and == | != It is considered best practice to always use the former set when comparing.

如果2个运算对象具有相同类型和值,则===返回true 且!==返回false.

"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

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. 避免简写方式

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';

总是考虑未来

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. 使用 JS Lint检查代码

JSLint is a debugger written by Douglas Crockford. Simply paste in your script, and it'll quickly scan for any noticeable issues and errors in your code.

"JSLint takes a JavaScript source and scans it. If it finds a problem, it returns a message describing the problem and an approximate location within the source. The problem is not necessarily a syntax error, although it often is. JSLint looks at some style conventions as well as structural problems. It does not prove that your program is correct. It just provides another set of eyes to help spot problems."

- JSLint Documentation

Before signing off on a script, run it through JSLint just to be sure that you haven't made any mindless mistakes.

5. 将script脚本放到页面底部

This tip has already been recommended in the previous article in this series. As it's highly appropriate though, I'll paste in the information.

Remember -- the primary goal is to make the page load as quickly as possible for the user. When loading a script, the browser can't continue on until the entire file has been loaded. Thus, the user will have to wait longer before noticing any progress.

If you have JS files whose only purpose is to add functionality -- for example, after a button is clicked -- go ahead and place those files at the bottom, just before the closing body tag. This is absolutely a best practice.

推荐:

<p>And now you know my favorite kinds of corn. </p>
<script type="text/javascript" src="path/to/file.js"></script>
<script type="text/javascript" src="path/to/anotherFile.js"></script>
</body>
</html>

6. 在for语句体外声明变量

When executing lengthy "for" statements, don't make the engine work any harder than it must. For example:

不推荐:

for(var i = 0; i < someArray.length; i++) {
   var container = document.getElementById('container');
   container.innerHtml += 'my number: ' + i;
   console.log(i);
}

Notice how we must determine the length of the array for each iteration, and how we traverse the dom to find the "container" element each time -- highly inefficient!

推荐:

var container = document.getElementById('container');
for(var i = 0, len = someArray.length; i < len;  i++) {
   container.innerHtml += 'my number: ' + i;
   console.log(i);
}

Bonus points to the person who leaves a comment showing us how we can further improve the code block above.

7. 最快构建String方式

Don't always reach for your handy-dandy "for" statement when you need to loop through an array or object. Be creative and find the quickest solution for the job at hand.

var arr = ['item 1', 'item 2', 'item 3', ...];
var list = '<ul><li>' + arr.join('</li><li>') + '</li></ul>';

I won’t bore you with benchmarks; you’ll just have to believe me (or test for yourself) - this is by far the fastest method!

Using native methods (like join()), regardless of what’s going on behind the abstraction layer, is usually much faster than any non-native alternative.

- James Padolsey, james.padolsey.com

8. 减少全局变量

"By reducing your global footprint to a single name, you significantly reduce the chance of bad interactions with other applications, widgets, or libraries."

- Douglas Crockford

var name = 'Jeffrey';
var lastName = 'Way';

function doSomething() {...}

console.log(name); // Jeffrey -- or window.name

推荐:

var DudeNameSpace = {
   name : 'Jeffrey',
   lastName : 'Way',
   doSomething : function() {...}
}
console.log(DudeNameSpace.name); // Jeffrey

Notice how we've "reduced our footprint" to just the ridiculously named "DudeNameSpace" object.

9. 添加注释

It might seem unnecessary at first, but trust me, you WANT to comment your code as best as possible. What happens when you return to the project months later, only to find that you can't easily remember what your line of thinking was. Or, what if one of your colleagues needs to revise your code? Always, always comment important sections of your code.

// Cycle through array and echo out each name.
for(var i = 0, len = array.length; i < len; i++) {
   console.log(array[i]);
}

10.拥抱渐进增强Embrace Progressive Enhancement

Always compensate for when JavaScript is disabled. It might be tempting to think, "The majority of my viewers have JavaScript enabled, so I won't worry about it." However, this would be a huge mistake.

Have you taken a moment to view your beautiful slider with JavaScript turned off? (Download the Web Developer Toolbar for an easy way to do so.) It might break your site completely. As a rule of thumb, design your site assuming that JavaScript will be disabled. Then, once you've done so, begin to progressively enhance your layout!

11. 不要向SetInterval或SetTimeOut传入字符串

Consider the following code:

setInterval(
"document.getElementById('container').innerHTML += 'My new number: ' + i", 3000
);

Not only is this code inefficient, but it also functions in the same way as the "eval" function would. Never pass a string to SetInterval and SetTimeOut. Instead, pass a function name.

setInterval(someFunction, 3000);

12. 避免使用With语句

At first glance, "With" statements seem like a smart idea. The basic concept is that they can be used to provide a shorthand for accessing deeply nested objects. For example...

with (being.person.man.bodyparts) {
   arms = true;
   legs = true;
}

-- instead of --

being.person.man.bodyparts.arms = true;
being.person.man.bodyparts.legs= true;

Unfortunately, after some testing, it was found that they "behave very badly when setting new members." Instead, you should use var.

var o = being.person.man.bodyparts;
o.arms = true;
o.legs = true;

13. 使用 {} 替代 New Object()

There are multiple ways to create objects in JavaScript. Perhaps the more traditional method is to use the "new" constructor, like so:

var o = new Object();
o.name = 'Jeffrey';
o.lastName = 'Way';
o.someFunction = function() {
   console.log(this.name);
}

However, this method receives the "bad practice" stamp without actually being so. Instead, I recommend that you use the much more robust object literal method.

推荐

var o = {
   name: 'Jeffrey',
   lastName = 'Way',
   someFunction : function() {
      console.log(this.name);
   }
};

Note that if you simply want to create an empty object, {} will do the trick.

var o = {};

"Objects literals enable us to write code that supports lots of features yet still make it a relatively straightforward for the implementers of our code. No need to invoke constructors directly or maintain the correct order of arguments passed to functions, etc." - dyn-web.com

14. 使用[] 替代 New Array()

The same applies for creating a new array.

Okay

var a = new Array();
a[0] = "Joe";
a[1] = 'Plumber';

推荐:

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. 一次性声明多个变量使用逗号分隔

var someItem = 'some string';
var anotherItem = 'another string';
var oneMoreItem = 'one more string';

推荐:

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. 记得一直要加分号

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" 语句

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. 使用 Firebug's "Timer" 功能优化代码

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. 读书,读书,读书...

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.

  • Object-Oriented JavaScript
  • JavaScript: The Good Parts
  • Learning jQuery 1.3
  • Learning JavaScript
Read them...multiple times. I still do!
21. 自我执行函数
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. 原生JavaScript永远比第三方类库更快
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 += '<li>' + response[i].name + ' : ' + response[i].email + '</li>';
}

24. 去掉 "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

24个javascript最佳实践相关推荐

  1. web前端开发最佳实践--(笔记之JavaScript最佳实践)

    如何避免全局变量污染? 避免定义全局变量或全局函数 用一个变量进行封装,并返回外部需要访问的接口 如何写出高维护的js代码 配置数据和代码逻辑分离 如: 改成: --- 用js模板 mustache ...

  2. JavaScript 初学者应知的 24 条最佳实践

    原文:24 JavaScript Best Practices for Beginners (注:阅读原文的时候没有注意发布日期,觉得不错就翻译了,翻译到 JSON.parse 那一节觉得有点不对路才 ...

  3. 给javascript初学者的24条最佳实践

    1.使用 === 代替 == JavaScript 使用2种不同的等值运算符:===|!== 和 ==|!=,在比较操作中使用前者是最佳实践. "如果两边的操作数具有相同的类型和值,===返 ...

  4. [译]编写优雅的JavaScript代码 - 最佳实践

    [原文]: devinduct.com/blogpost/22- 有没有似曾相识 如果你对于代码,除了关注是否能准确的执行业务逻辑,还关心代码本身是怎么写的,是否易读,那么你应该会关注如何写出干净优雅 ...

  5. 前端代码标准最佳实践:javascript篇

    2019独角兽企业重金招聘Python工程师标准>>> 前言 最近一直重构项目的前端代码,也参考了各种前端代码的最佳实践,目的是让前端的HTML,CSS,Javacript代码更符合 ...

  6. 超实用的JavaScript技巧及最佳实践

    众所周知,JavaScript是一门非常流行的编程语言,开发者用它不仅可以开发出炫丽的Web程序,还可以用它来开发一些移动应用程序(如PhoneGap或Appcelerator),它还有一些服务端实现 ...

  7. Spotfire在文本区域添加自定义JavaScript代码的最佳实践

    这边文章包含了如何在TIBCO Spotfire分析文件的文本区域中以一种可支持和可维护的方式来开发自定义JavaScript代码的最佳实践和建议,因此,这些分析文件将持续与TIBCO Spotfir ...

  8. plupload 不兼容ie8_Cocos Creator 最佳实践:JavaScript兼容性问题规避

    本篇文章来源于腾讯在线教育技术 ,作者 josephpan. 本文从 Cocos Creator 开发的角度出发,仔细探讨了关注 JavaScript API 兼容性的必要性,以及如何借助工具和 Po ...

  9. RESTful服务最佳实践

    本文主要读者 引言 REST是什么 统一接口 基于资源 通过表征来操作资源 自描述的信息 超媒体即应用状态引擎(HATEOAS) 无状态 可缓存 C-S架构 分层系统 按需编码(可选) REST快速提 ...

最新文章

  1. ASP.NET 弹出窗口
  2. MATLAB读取文本文件----textread
  3. 智能搜索模型预估框架的建设与实践
  4. “Paper + Code”才是研读论文的正确姿势 | PaperDaily #02
  5. spring之集合注入
  6. BeginnersBook MongoDB 教程
  7. 量化投资_波动和趋势能量比(传统盘整和趋势的量化表示)
  8. 百度DuerOS与高通合推手机语音交互解决方案,谁会欢喜谁要愁?
  9. 设计模式7大结构型模式
  10. 现代3D图形编程学习-基础简介(2) (译)
  11. Mac没有winnt格式_Mac视频格式转换工具-H265 Converter Pro
  12. 宝塔面板部署网易云api
  13. 关于GitHub如何转为中文问题——Google举例
  14. python爬取网易云音乐飙升榜音乐,网易云音乐-飙升榜歌曲信息爬取
  15. 在MAME里如何设置组合键
  16. Keil出现Error:Flash Download failed - Could not load file
  17. 产品经理如何写好产品需求文档
  18. Anbox源码分析(三)——Anbox渲染原理(源码分析)
  19. 7-1 计算物体自由下落的距离
  20. 前端框架Vue中各个文件夹的具体作用简介

热门文章

  1. 两台电脑连接时,A电脑可以ping通B电脑,而B电脑pingA电脑时出现超时问题,解决:
  2. 【必看干货】在我面了10多家大厂(上岸)后,我吐血总结你要是这12道题都不能拿满分,那你就与大厂算法无缘了 ——AI视觉算法工程师
  3. ssm城市旅游景点信息交流平台的设计与实现毕业设计源码290915
  4. 2017年的端午节祝福语
  5. php求解鸡鸭同笼,鸡兔同笼的9种解法
  6. eclipse java配色_eclips配色
  7. Android开发技巧——定制仿微信图片裁剪控件
  8. 文件搜索与文本内容查看
  9. 多协议BGP-----MPBGP
  10. 关于第一次面试总结(嵌入式软件开发工程师)