24个javascript最佳实践
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
使用 === 代替 ==
避免使用Eval
避免简写方式
x = false
x = false
anotherFunctionCall();
x = false;
anotherFunctionCall();
}
x = false;
}
anotherFunctionCall();
使用 JS Lint检查代码
将script脚本放到页面底部
<script type="text/javascript" src="path/to/file.js"></script>
<script type="text/javascript" src="path/to/anotherFile.js"></script>
</body>
</html>
在for语句体外声明变量
var container = document.getElementById('container');
container.innerHtml += 'my number: ' + i;
console.log(i);
}
for(var i = 0, len = someArray.length; i < len; i++) {
container.innerHtml += 'my number: ' + i;
console.log(i);
}
最快构建String方式
var list = '<ul><li>' + arr.join('</li><li>') + '</li></ul>';
减少全局变量
var lastName = 'Way';
function doSomething() {...}
console.log(name); // Jeffrey -- or window.name
name : 'Jeffrey',
lastName : 'Way',
doSomething : function() {...}
}
console.log(DudeNameSpace.name); // Jeffrey
添加注释
for(var i = 0, len = array.length; i < len; i++) {
console.log(array[i]);
}
拥抱渐进增强Embrace Progressive Enhancement
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!
不要向SetInterval或SetTimeOut传入字符串
"document.getElementById('container').innerHTML += 'My new number: ' + i", 3000
);
避免使用With语句
arms = true;
legs = true;
}
being.person.man.bodyparts.legs= true;
o.arms = true;
o.legs = true;
使用 {} 替代 New Object()
o.name = 'Jeffrey';
o.lastName = 'Way';
o.someFunction = function() {
console.log(this.name);
}
name: 'Jeffrey',
lastName = 'Way',
someFunction : function() {
console.log(this.name);
}
};
dyn-web.com
使用[] 替代 New Array()
a[0] = "Joe";
a[1] = 'Plumber';
一次性声明多个变量使用逗号分隔
var anotherItem = 'another string';
var oneMoreItem = 'one more string';
anotherItem = 'another string',
oneMoreItem = 'one more string';
记得一直要加分号
function doSomething() {
return 'something'
}
function doSomething() {
return 'something';
}
"For in" 语句
if(object.hasOwnProperty(key) {
...then do something...
}
}
使用 Firebug's "Timer" 功能优化代码
console.time("MyTimer");
for(x=5000; x > 0; x--){}
console.timeEnd("MyTimer");
}
读书,读书,读书...
自我执行函数
return {
name: 'jeff',
lastName: 'way'
};
})();
原生JavaScript永远比第三方类库更快
使用Crockford's JSON.Parse
HERE.
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>';
}
去掉 "Language"
...
</script>
24个javascript最佳实践的更多相关文章
- JavaScript 最佳实践
这个文档是基于JavaScript社区众多开发者的意见和经验,在开发JavaScript代码上的最佳实践和首选的方案的明细表.因为这是一个推荐的表而非原则性的方案,经验丰富的开发者可能对下面的表达会有 ...
- javascript 最佳实践 ( 24 章 )
代码约定 易于维护, 形成了一套 JavaScript 代码书写的约定: 跟别的语言差不多, 不过 javascript 中的大括号一定要放在 行尾, 例如: function abc() { // ...
- 【原】javascript最佳实践
摘要:这篇文章主要内容的来源是<javascript高级程序设计第三版>,因为第二遍读完,按照书里面的规范,发觉自己在工作中没有好好遵守.所以此文也是对自己书写js的一种矫正. 1.可维护 ...
- JavaScript最佳实践:可维护性
代码约定 一.可读性 代码缩进 包含注释 二.变量和函数命名 变量名应为名词如car或person 函数名应该以动词开始,如getName().返回布尔类型值的函数一般以is开头,如isEnable( ...
- JavaScript最佳实践
作者:Grey 原文地址: http://www.cnblogs.com/greyzeng/p/5540469.html 举个例子:用户在点击某个链接的时候弹出一个新窗口 弹出窗口的方法采用:wind ...
- 15条JavaScript最佳实践很经典噢
感觉比较经典,特转载腾讯大讲堂.本文档整理大部分公认的.或者少有争议的JavaScript良好书写规范(Best Practice).一些显而易见的常识就不再论述(比如要用对象支持识别判断,而不是浏览 ...
- 学习JavaScript最佳实践方法
首先要说明的是,咱现在不是高手,最多还是一个半桶水,算是入了JS的门. 谈不上经验,都是一些教训. 这个时候有人要说,“靠,你丫半桶水,凭啥教我们”.您先别急着骂,先听我说. 你叫一个大学生去教小学数 ...
- 15条JavaScript最佳实践【转】
本文档整理大部分公认的.或者少有争议的JavaScript良好书写规范(Best Practice).一些显而易见的常识就不再论述(比如要用对象支持识别判断,而不是浏览器识别判断:比如不要嵌套太深). ...
- 给JavaScript初学者的24条最佳实践
.fluid-width-video-wrapper { width: 100%; position: relative; padding: 0 } .fluid-width-video-wrapp ...
- 给JavaScript初学者的24条最佳实践(share)
不错的文章,留个备份 原文链接: net.tutsplus 翻译: 伯乐在线- yanhaijing译文链接: http://blog.jobbole.com/53199/ 作为“30 HTML和 ...
随机推荐
- Go-GC
- [转帖]OceanBase 存储引擎详解
https://zhuanlan.zhihu.com/p/436485359 作者简介:沈炼,蚂蚁集团技术风险部数据库高级专家毕业于东南大学,2014年以来从事 OceanBase 在蚂蚁的架构工作, ...
- [转帖]Linux中查看各文件夹大小命令du -h --max-depth=1
https://www.cnblogs.com/the-tops/p/8798678.html 最近排查服务器异常的时候,常会遇到磁盘慢的情况,这个时候,查找那个文件夹占用的内存的时候常用到这个命令: ...
- [转帖]decimal and numeric (Transact-SQL)
https://learn.microsoft.com/en-us/sql/t-sql/data-types/decimal-and-numeric-transact-sql?view=sql-ser ...
- [转帖]整理常用的 vim 命令
vim 是一款功能强大的文本编辑器,它是Linux下常用的编辑器之一,对于熟练掌握了 vim 的人来说,用它编辑文件,方便又快捷,能极大的提高工作效率 vim 功能强大,对应的命令也非常的多,对于初学 ...
- [转帖]HTTP与HTTPS超文本传输协议的区别是什么
https://www.likecs.com/show-308649882.html 随着越来越多的网站使用HTTPS加密,现在HTTPS的使用已经成了硬性要求了.虽然说https是http的安全版, ...
- Linux时间戳转换成易读格式的方法
背景 最近一直在学习Redis相关的知识. 其中遇到了一个redis monitor的命令 但是这里有一个问题是: 原生命令查询出来的时间是Unix时间戳格式的. 不太好发现查看与进行对照. 所以今天 ...
- Linux查看登录用户记录信息
Linux查看登录用户记录信息 登录成功的信息 last 可以简单统计一下: last |awk '{print $3}' |sort |uniq -c |sort -k1nr 登录失败的 就是 la ...
- JQuery 源码解析一
网上已经有很多解读 jQuery 源码的文章了,作为系列开篇的第一篇,思前想去起了个[深入浅出jQuery]的标题,资历尚浅,无法对 jQuery 分析的头头是道,但是 jQuery 源码当中确实有着 ...
- C# 输入指定日期获取当前年的第一天 、当前年的最后天、某月的第一天 、某月的最后一天
方法 /// <summary> /// 取得当前年的第一天 /// </summary> /// <param name="datetime"> ...