jassonfish

导航

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

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

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

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

// bad code
if(someVariableExists)   
   x = false 

// good code
if(someVariableExists) {  
   x = false; 
}

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)

<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循环外部声明变量(Declare Variabs outside of the For statement)

// 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);
}

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)

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

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”)

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

// good code
setInterval(someFunction.3000);

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

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

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

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

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

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

//better code
var a = ['Joe','Plumber'];

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

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

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

var someItem = 'some string'
function doSomething() {
  return 'something'
}

//better code
var someItem = 'some string';
function doSomething() {
  return 'something';
}

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.

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

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:

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

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:

// 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() 
*/

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/

posted on 2014-01-20 16:36  jassonfish  阅读(389)  评论(0编辑  收藏  举报