Home >Web Front-end >JS Tutorial >Some best practices for JavaScript beginners
1. Use === instead of ==
JavaScript uses 2 different equality operators: ===|!== and ==|!=. It is a best practice to use the former in comparison operations.
"If the operands on both sides have the same type and value, === returns true, !== returns false." - "JavaScript: The Essence of the Language"
However, when using == and! =, you may encounter a situation where the types are different. In this case, the types of the operands will be forced to be the same and then compared, which may not be the result you want.
2.Eval=Evil
When not familiar at first, “eval” gives us access to the JavaScript compiler (Annotation: This seems very powerful). Essentially, we can pass a string to eval as a parameter while executing it.
Not only does this greatly reduce the performance of the script (Annotation: The JIT compiler cannot predict the content of the string and cannot precompile and optimize), but it also brings huge security risks because the payout for the text to be executed is too high. authority, stay away.
3. Omission may not save trouble
Technically, you can omit most curly braces and semicolons. Most browsers will correctly understand the following code:
if(someVariableExists) x = false
Then, if it looks like this:
if(someVariableExists) x = false anotherFunctionCall();
Someone might think that the above code is equivalent to the following:
if(someVariableExists) { x = false; anotherFunctionCall(); }
Unfortunately, this understanding is wrong of. The actual meaning is as follows:
if(someVariableExists) { x = false; } anotherFunctionCall();
You may have noticed that the indentation above easily gives the illusion of curly braces. Justifiably so, this is a terrible practice and should be avoided at all costs. There is only one case in which the curly braces can be omitted, that is, when there is only one line, but this is controversial.
if(2 + 2 === 4) return 'nicely done';
Plan for a rainy day
Most likely, one day you will need to add more statements to the if block. In this case, you must rewrite this code. Bottom line – omissions are a minefield.
4. Use JSLint
JSLint is a debugger written by the famous Douglas Crockford. Simply paste your code into JSLint and it will quickly find obvious problems and errors in your code.
“JSLint scans the input source code. If it finds a problem, it returns a message describing the problem and its location in the code. The problem is not necessarily a syntax error, although that often is. JSLint also looks at some encoding Style and program structure issues. This doesn't guarantee that your program is correct. It just provides another pair of eyes to help spot problems." - JSLing Documentation
Run JSLint before deploying the script, just to make sure you haven't made it. Any stupid mistakes.
5. Place the script at the bottom of the page
Remember - the primary goal is to make the page presented to the user as quickly as possible. The loading of the script is blocked. The browser cannot continue until the script is loaded and executed. Render the content below. Therefore, users will be forced to wait longer.
If your js is only used to enhance the effect - for example, a button click event - immediately place the script before the end of the body. This is definitely best practice.
Recommendation
<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. Avoid declaring variables within a For statement
When executing a lengthy for statement, keep the statement block as concise as possible, for example:
Oops
for(var i = 0; i < someArray.length; i++) { var container = document.getElementById('container'); container.innerHtml += 'my number: ' + i; console.log(i); }
Note that the array must be calculated every time it loops length, and each time the DOM must be traversed to query the "container" element - the efficiency is seriously low!
Suggestion
var container = document.getElementById('container'); for(var i = 0, len = someArray.length; i < len; i++) { container.innerHtml += 'my number: ' + i; console.log(i); }
If you are interested, you can think about how to continue to optimize the above code. Please leave a comment to share.
7. The best way to construct a string
When you need to traverse an array or object, don’t always think about the “for” statement. Be creative and you can always find a better way, for example, like the following.
var arr = ['item 1', 'item 2', 'item 3', ...]; var list = '<ul><li>' + arr.join('</li><li>') + '</li></ul>';
I am not the god in your mind, but please believe me (test it yourself if you don’t believe me) - this is by far the fastest method! Using native code (such as join()), regardless of what the system does internally, is usually much faster than non-native. ——James Padolsey, james.padolsey.com
8. Reduce global variables
As long as multiple global variables are organized under one namespace, it will significantly reduce conflicts with other applications, components or class libraries. the possibility of mutual influence. ——Douglas Crockford
var name = 'Jeffrey'; var lastName = 'Way'; function doSomething() {...} console.log(name); // Jeffrey -- 或 window.name
Better approach
var DudeNameSpace = { name : 'Jeffrey', lastName : 'Way', doSomething : function() {...} } console.log(DudeNameSpace.name); // Jeffrey
Note: This is simply named “DudeNameSpace”. In practice, a more reasonable name should be used.
9. Add comments to the code
似乎没有必要,当请相信我,尽量给你的代码添加更合理的注释。当几个月后,重看你的项目,你可能记不清当初你的思路。或者,假如你的一位同事需要修改你的代码呢?总而言之,给代码添加注释是重要的部分。
// 循环数组,输出每项名字(译者注:这样的注释似乎有点多余吧). for(var i = 0, len = array.length; i < len; i++) { console.log(array[i]); }
10.拥抱渐进增强
确保javascript被禁用的情况下能平稳退化。我们总是被这样的想法吸引,“大多数我的访客已经启用JavaScript,所以我不必担心。”然而,这是个很大的误区。
你可曾花费片刻查看下你漂亮的页面在javascript被关闭时是什么样的吗?(下载 Web Developer 工具就能很容易做到(译者注:chrome用户在应用商店里自行下载,ie用户在Internet选项中设置)),这有可能让你的网站支离破碎。作为一个经验法则,设计你的网站时假设JavaScript是被禁用的,然后,在此基础上,逐步增强你的网站。
11.不要给”setInterval”或”setTimeout”传递字符串参数
考虑下面的代码:
setInterval( "document.getElementById('container').innerHTML += 'My new number: ' + i", 3000 );
不仅效率低下,而且这种做法和”eval”如出一辙。从不给setInterval和setTimeout传递字符串作为参数,而是像下面这样传递函数名。
setInterval(someFunction, 3000);
12.不要使用”with”语句
乍一看,”with”语句看起来像一个聪明的主意。基本理念是,它可以为访问深度嵌套对象提供缩写,例如……
with (being.person.man.bodyparts) { arms = true; legs = true; }
而不是像下面这样:
being.person.man.bodyparts.arms = true; being.person.man.bodyparts.legs= true;
不幸的是,经过测试后,发现这时“设置新成员时表现得非常糟糕。作为代替,您应该使用变量,像下面这样。
var o = being.person.man.bodyparts; o.arms = true; o.legs = true;
13.使用{}代替 new Ojbect()
在JavaScript中创建对象的方法有多种。可能是传统的方法是使用”new”加构造函数,像下面这样:
var o = new Object(); o.name = 'Jeffrey'; o.lastName = 'Way'; o.someFunction = function() { console.log(this.name); }
然而,这种方法的受到的诟病不及实际上多。作为代替,我建议你使用更健壮的对象字面量方法。
更好的做法
var o = { name: 'Jeffrey', lastName = 'Way', someFunction : function() { console.log(this.name); } };
注意,果你只是想创建一个空对象,{}更好。
var o = {};
“对象字面量使我们能够编写更具特色的代码,而且相对简单的多。不需要直接调用构造函数或维持传递给函数的参数的正确顺序,等”——dyn-web.com
14.使用[]代替 new Array()
这同样适用于创建一个新的数组。
例如:
var a = new Array(); a[0] = "Joe"; a[1] = 'Plumber';
更好的做法:
var a = ['Joe','Plumber'];
“javascript程序中常见的错误是在需要对象的时候使用数组,而需要数组的时候却使用对象。规则很简单:当属性名是连续的整数时,你应该使用数组。否则,请使用对象”——Douglas Crockford
15.定义多个变量时,省略var关键字,用逗号代替
var someItem = 'some string'; var anotherItem = 'another string'; var oneMoreItem = 'one more string';
更好的做法
var someItem = 'some string', anotherItem = 'another string', oneMoreItem = 'one more string';
…应而不言自明。我怀疑这里真的有所提速,但它能是你的代码更清晰。
16.谨记,不要省略分号
从技术上讲,大多数浏览器允许你省略分号。
var someItem = 'some string' function doSomething() { return 'something' }
已经说过,这是一个非常糟糕的做法可能会导致更大的,难以发现的问题。
更好的做法
var someItem = 'some string'; function doSomething() { return 'something'; }
17.”For in”语句
当遍历对象的属性时,你可能会发现还会检索方法函数。为了解决这个问题,总在你的代码里包裹在一个if语句来过滤信息。
for(key in object) { if(object.hasOwnProperty(key) { ...then do something... } }
参考 JavaScript:语言精粹,道格拉斯(Douglas Crockford)。
18.使用Firebug的”timer”功能优化你的代码
在寻找一个快速、简单的方法来确定操作需要多长时间吗?使用Firebug的“timer”功能来记录结果。
function TimeTracker(){ console.time("MyTimer"); for(x=5000; x > 0; x--){} console.timeEnd("MyTimer"); }
19.阅读,阅读,反复阅读
虽然我是一个巨大的web开发博客的粉丝(像这样!),午餐之余或上床睡觉之前,实在没有什么比一本书更合适了,坚持放一本web开发方面书在你的床头柜。下面是一些我最喜爱的JavaScript书籍。
《Object-Oriented JavaScript | JavaScript面向对象编程指南》
《JavaScript:The Good Parts | JavaScript语言精粹 修订版》
《Learning jQuery 1.3 |jQuery基础教程 第4版》
《Learning JavaScript |JavaScript学习指南》
读了他们……多次。我仍将继续!
20.自执行函数
和调用一个函数类似,它很简单的使一个函数在页面加载或父函数被调用时自动运行。简单的将你的函数用圆括号包裹起来,然后添加一个额外的设置,这本质上就是调用函数。
(function doSomething() { return { name: 'jeff', lastName: 'way' }; })();
21.原生代码永远比库快
JavaScript库,例如jQuery和Mootools等可以节省大量的编码时间,特别是AJAX操作。已经说过,总是记住,库永远不可能比原生JavaScript代码更快(假设你的代码正确)。
jQuery的“each”方法是伟大的循环,但使用原生”for”语句总是更快。
22.道格拉斯的 JSON.Parse
尽管JavaScript 2(ES5)已经内置了JSON 解析器。但在撰写本文时,我们仍然需要自己实现(兼容性)。道格拉斯(Douglas Crockford),JSON之父,已经创建了一个你可以直接使用的解析器。这里可以下载(链接已坏,可以在这里查看相关信息http://www.json.org/)。
只需简单导入脚本,您将获得一个新的全局JSON对象,然后可以用来解析您的json文件。
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>'; }