首页 > Web开发 > 详细

25条Javascript 编码规律(javascript best practice for beginner)

时间:2014-01-21 16:32:40      阅读:458      评论:0      收藏:0      [点我收藏+]

1.使用“===”代替“==”(use === instead of ==)

2. 避免使用eval (Eval = bad)

3.不要用缩略局(Dont use short-Hand)

bubuko.com,布布扣
// bad code
if(someVariableExists)   
   x = false 

// good code
if(someVariableExists) {  
   x = false; 
}
bubuko.com,布布扣

4.使用 JS Lint (utilize 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.

5. 将script代码放置到你页面的底部(Place Scripts at the bottom of your page)

bubuko.com,布布扣
<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>
bubuko.com,布布扣

6. 在For循环外部声明变量(Declare Variabs outside of the For statement)

bubuko.com,布布扣
// bad code
for(var i = 0; i < someArray.length; i++) {
   var container = document.getElementById(‘container‘);
   container.innerHtml += ‘my number: ‘ + i;
   console.log(i);
}

//better code
var container = document.getElementById(‘container‘);
for(var i = 0, len = someArray.length; i < len;  i++) {
   container.innerHtml += ‘my number: ‘ + i;
   console.log(i);
}
bubuko.com,布布扣

7. 最快速的方式构建String(the fastest way to build a String)

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

8. 减少全局变量(reduce globals)

bubuko.com,布布扣
var name = ‘Jeffrey‘;
var lastName = ‘Way‘;

function doSomething() {...}

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


// better code
var DudeNameSpace = {
   name : ‘Jeffrey‘,
   lastName : ‘Way‘,
   doSomething : function() {...}
}
console.log(DudeNameSpace.name); // Jeffrey
bubuko.com,布布扣

9. 为你的代码添加注释(comment 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. 不要在“setInterval” 或“setTimeout”的函数中使用字符串(Dont pass a String to “SetInterval” or “SetTimeOut”)

bubuko.com,布布扣
// bad code
setInterval(   
"document.getElementById(‘container‘).innerHTML += ‘My new number: ‘ + i", 3000   
);

// good code
setInterval(someFunction.3000);
bubuko.com,布布扣

11. 不要用“With” 语句(Dont use the “With” statement)

bubuko.com,布布扣
//bad code
with (being.person.man.bodyparts) {
   arms = true;
   legs = true;
}

// better code
being.person.man.bodyparts.arms = true;
being.person.man.bodyparts.legs= true;

// best code 
var o = being.person.man.bodyparts;
o.arms = true;
o.legs = true;
bubuko.com,布布扣

12. 使用{} 代替 New Object() (use {} instead of New Object())

bubuko.com,布布扣
var o = new Object();
o.name = ‘Jeffrey‘;
o.lastName = ‘Way‘;
o.someFunction = function() {
   console.log(this.name);
}

//better code
var o = {
   name: ‘Jeffrey‘,
   lastName = ‘Way‘,
   someFunction : function() {
      console.log(this.name);
   }
};
bubuko.com,布布扣

13. 使用[] 代替 new Array() (use [] instead of new Array()

bubuko.com,布布扣
//okay
var a = new Array();
a[0] = "Joe";
a[1] = ‘Plumber‘;

//better code
var a = [‘Joe‘,‘Plumber‘];
bubuko.com,布布扣

14. 如何处理一堆的变量声明?省略“var”关键字并用逗号代替(Long list of variables?Omit the "var" keyword and use commas instead

bubuko.com,布布扣
var someItem = ‘some string‘;
var anotherItem = ‘another string‘;
var oneMoreItem = ‘one more string‘;

// better code
var someItem = ‘some string‘,
    anotherItem = ‘another string‘,
    oneMoreItem = ‘one more string‘;
bubuko.com,布布扣

15. 切记,切记一定用分号(always,always use semicolons)

bubuko.com,布布扣
var someItem = ‘some string‘
function doSomething() {
  return ‘something‘
}

//better code
var someItem = ‘some string‘;
function doSomething() {
  return ‘something‘;
}
bubuko.com,布布扣

16. “For in” 语句 ("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...
   }
}

17. 使用Firebug的 timer 特性去优化你的代码(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");
}

18. 自执行函数

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‘
   };
})();

20. 原始的javascript总是比应用库更快。(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.

21. 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.

bubuko.com,布布扣
 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>‘;
 }
bubuko.com,布布扣

22. 去除“language”(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.

23. 循环语句(for Loops)

 

In for loops you iterate over arrays or array-like objects such as arguments and HTMLCollection objects. The usual for loop pattern looks like the following:

// sub-optimal loop 
for (var i = 0; i < myarray.length; i++) {
   // do something with myarray[i]
}

A problem with this pattern is that the length of the array is accessed on every loop iteration. This can slow down your code, especially when myarray is not an array but an HTMLCollection object.

HTMLCollections are objects returned by DOM methods such as:

  • document.getElementsByName()
  • document.getElementsByClassName()
  • document.getElementsByTagName()

There are also a number of other HTMLCollections, which were introduced before the DOM standard and are still in use today. There include (among others):

  • document.images: All IMG elements on the page
  • document.links : All A elements
  • document.forms : All forms
  • document.forms[0].elements : All fields in the first form on the page

The trouble with collections is that they are live queries against the underlying document (the HTML page). This means that every time you access any collection’s length, you’re querying the live DOM, and DOM operations are expensive in general.

That’s why a better pattern for for loops is to cache the length of the array (or collection) you’re iterating over, as shown in the following example:

for (var i = 0, max = myarray.length; i < max; i++) {
   // do something with myarray[i] 
}

This way you retrieve the value of length only once and use it during the whole loop.

Caching the length when iterating over HTMLCollections is faster across all browsers— anywhere between two times faster (Safari 3) and 190 times (IE7).

Note that when you explicitly intend to modify the collection in the loop (for example, by adding more DOM elements), you’d probably like the length to be updated and not constant.

Following the single var pattern, you can also take the var out of the loop and make the loop like:

bubuko.com,布布扣
function looper() { 
   var i = 0,
        max, 
        myarray = [];
   // ...
   for (i = 0, max = myarray.length; i < max; i++) {
      // do something with myarray[i]
   }
}
bubuko.com,布布扣

This pattern has the benefit of consistency because you stick to the single var pattern. A drawback is that it makes it a little harder to copy and paste whole loops while refactoring code. For example, if you’re copying the loop from one function to another, you have to make sure you also carry over i and max into the new function (and probably delete them from the original function if they are no longer needed there).

One last tweak to the loop would be to substitute i++ with either one of these expressions:

i=i+ 1    
i += 1 

JSLint prompts you to do it; the reason being that ++ and -- promote “excessive trickiness.” If you disagree with this, you can set the JSLint option plusplus to false. (It’s true by default.)

Two variations of the for pattern introduce some micro-optimizations because they:

  • Use one less variable (no max)
  • Count down to 0, which is usually faster because it’s more efficient to compare to 0 than to the length of the array or to anything other than 0

The first modified pattern is:

var i, myarray = []; 
for (i = myarray.length; i--;) {
   // do something with myarray[i]

And the second uses a while loop:

var myarray = [],
    i = myarray.length; 
while (i--) {
   // do something with myarray[i]
}

These are micro-optimizations and will only be noticed in performance-critical operations. Additionally, JSLint will complain about the use of i--.

24. for-in 循环语句(for-in Loops)

 

for-in loops should be used to iterate over nonarray objects. Looping with for-in is also called enumeration.

It’s important to use the method hasOwnProperty() when iterating over object properties to filter out properties that come down the prototype chain.

Consider the following example:

bubuko.com,布布扣
// the object 
var man = {
   hands: 2, 
   legs: 2, 
   heads: 1
};

// somewhere else in the code,a method was added to all objects 
if (typeof Object.prototype.clone === "undefined") {
   Object.prototype.clone = function () {};
}

// 1.  for-in loop 
for (var i in man) {
   if (man.hasOwnProperty(i)) { // filter
      console.log(i, ":", man[i]);
   }
} 

/* result in the console 
hands : 2 
legs : 2 
heads : 1 
*/

// 2.  antipattern:  for-in loop without checking hasOwnProperty() 
for (var i in man) {
   console.log(i, ":", man[i]);
} 

/* 
result in the console 
hands : 2 
legs : 2 
heads : 1 
clone: function() 
*/
bubuko.com,布布扣

Another pattern for using hasOwnProperty() is to call that method off of the Object.prototype, like so:

for (var i in man) { 
   if (Object.prototype.hasOwnProperty.call(man, i)) { // filter
      console.log(i, ":", man[i]);
   }
}

The benefit is that you can avoid naming collisions is case the man object has redefined hasOwnProperty. Also to avoid the long property lookups all the way to Object, you can use a local variable to “cache” it:

var i, hasOwn = Object.prototype.hasOwnProperty;
for (i in man) {
    if (hasOwn.call(man, i)) { // filter
        console.log(i, ":", man[i]);
    }
}

Strictly speaking, not using hasOwnProperty() is not an error. Depending on the task and the confidence you have in the code, you may skip it and slightly speed up the loops. But when you’re not sure about the contents of the object (and its prototype chain), you’re safer just adding the hasOwnProperty() check.

25.(Not) Augmenting Built-in Prototypes

if (typeof Object.protoype.myMethod !== "function") { 
   Object.protoype.myMethod = function () {
      // implementation...
   };
}

 

 

 

 原帖地址:http://net.tutsplus.com/tutorials/javascript-ajax/24-javascript-best-practices-for-beginners/

25条Javascript 编码规律(javascript best practice for beginner)

原文:http://www.cnblogs.com/jassonfish/p/3527169.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!