javascript最佳实践(持续中....)

来源:互联网 发布:iphone笔记软件 编辑:程序博客网 时间:2024/05/24 03:19

理清了前因后果后,内容是特别庞大的,必须选择一个方向继续深入。javascript无疑是一个很好的方向,毕竟h5离不开它,微信小程序离不开它,全栈还是离不开它。所以进行了javascript基础的二刷,并参考w3school得到一些最佳实践:
1.It is a good idea to place scripts at the bottom of the element.
This can improve page load, because script compilation can slow down the display.
ps:浏览器加载页面的时候会同时加载使用到的资源,css,js等,将js写到head是一种常用写法,不过加载页面的时候会先载入head再执行body,所以js写在前面会影响到body的显示,让页面出现变慢。如果js写在body的最底部,则可以让静态的body先显示出来。另外,使用外部js时,要load这些文件可能要几百毫秒,如果一个页面使用了很多这类文件,那打开它累计的时间会很多,加载页面会慢,这个时候可以采用异步加载,不阻塞静态页面显示

2.Placing JavaScripts in external files has some advantages:
It separates HTML and code
It makes HTML and JavaScript easier to read and maintain
Cached JavaScript files can speed up page loads
ps:浏览器都可以缓存加载过的资源,外部js被缓存后,下次可以直接使用,这种方式显然会加快页面渲染速度。内部js代码则每次都要执行一遍。

3.Avoid Global Variables
This includes all data types, objects, and functions.
Global variables and functions can be overwritten by other scripts.
Use local variables instead, and learn how to use closures.
ps:避免使用全局变量,因为全局变量在多个js文件的时候可能会被重用,这个问题很难被发现,最后导致各种错误。当然了使用’use strict’可以帮忙辨识是否重用,最佳方案就是少用。如果某些场景不使用无法达到效果。
比如:做个累加器
如果使用全局变量

var counter = 0;function add() {    counter += 1;}add();   //counter = 1add();   //counter = 2add();   //counter = 3

如果使用局部变量

function add() {    var counter = 0;    counter += 1;}add();   //counter = 1add();   //counter = 1add();   //counter = 1

这个时候就尴尬了,解决方案是learn how to use closures(闭包).

var add = (function () {    var counter = 0;    return function () {return counter += 1;}})();add();   //counter = 1add();   //counter = 2add();   //counter = 3

闭包是个比较难理解的东东,详解在此:http://blog.csdn.net/kkae8643150/article/details/52636726

看完详解应该能理解闭包为什么可以达到效果。上述代码正确的原因在于,
add = (function(){})()外部匿名函数会立即执行
所以相当于add = function () {return counter += 1;} 这是个典型的闭包,访问了私有变量counter
由于counter被全局变量add持有,所以会一直保存在内存中不被清理掉,所以就有了全局变量的功效。

4.Always Declare Local Variables
All variables used in a function should be declared as local variables.
Local variables must be declared with the var keyword, otherwise they will become global variables.
ps:在function内部的局部变量一定要用var声明,否则会变成全局变量。

5.Declarations on Top
It is a good coding practice to put all declarations at the top of each script or function.
This will:
Give cleaner code
Provide a single place to look for local variables
Make it easier to avoid unwanted (implied) global variables
Reduce the possibility of unwanted re-declarations
ps:所有声明置于顶部,当然无论写在哪,By default, JavaScript moves all declarations to the top (JavaScript hoisting).

6.Initialize Variables
It is a good coding practice to initialize variables when you declare them.
This will:
Give cleaner code
Provide a single place to initialize variables
Avoid undefined values
ps:时刻记住初始化变量。这样做的好处在于,跟第5条结合起来看,不初始化有可能造成错误。

var a = 1;var c = function(){ return a+b};var b;b = 2;c();  //猜猜结果

原因就不解释了。

7.Never Declare Number, String, or Boolean Objects
Always treat numbers, strings, or booleans as primitive values. Not as objects.
Declaring these types as objects, slows down execution speed, and produces nasty side effects
ps:也就是说不要做这样的操作var s = new String(“”);,复制会造成效率下降,且它用于比较的时候会比较奇葩,主要是由于它的类型是Object

8.Don’t Use new Object()
Use {} instead of new Object()
Use “” instead of new String()
Use 0 instead of new Number()
Use false instead of new Boolean()
Use [] instead of new Array()
Use /()/ instead of new RegExp()
Use function (){} instead of new Function()

9.Beware of Automatic Type Conversions
Beware that numbers can accidentally be converted to strings or NaN (Not a Number).

JavaScript is loosely typed. A variable can contain different data types, and a variable can change its data type:

Example
var x = “Hello”; // typeof x is a string
x = 5; // changes typeof x to a number

10.se === Comparison
The == comparison operator always converts (to matching types) before comparison.
The === operator forces comparison of values and type
ps:==比较前会进行类型转换,===不会转换,同时比较类型和值,尽量用===

11.Use Parameter Defaults
If a function is called with a missing argument, the value of the missing argument is set to undefined.
Undefined values can break your code. It is a good habit to assign default values to arguments.
function myFunction(x, y) {
if (y === undefined) {
y = 0;
}
}
ps:在执行逻辑前,给function的每个参数附上一个默认值

12.End Your Switches with Defaults
Always end your switch statements with a default. Even if you think there is no need for it.
ps:所有语言都一样,switch要有default分支

13.Avoid Using eval()
The eval() function is used to run text as code. In almost all cases, it should not be necessary to use it.

Because it allows arbitrary code to be run, it also represents a security problem.

0 0
原创粉丝点击