序
大部分針對Javascript最合理的方法歸納。
類型
• 原始類型:我們可以直接使用值。
ο string
ο number
ο boolean
ο null
ο undefine
var foo = 1,
bar = foo;
bar = 9;
console.log(foo, bar); // => 1, 9
• 複合類型:我們通過`引用`對值進行間接通路。
ο object
ο array
ο function
var foo = [1, 2],
bar[0] = 9;
console.log(foo[0], bar[0]); // => 9, 9
Objects
• 使用{}建立對象。
// bad
var item = new Object();
// good
var item = {};
• 不要使用保留字作為關鍵字。
var superman = {
class: 'superhero',
default: { clark: 'kent' },
private: true
};
klass: 'superhero',
defaults: { clark: 'kent' },
hidden: true
Arrays
• 使用[]建立數組
var items = new Array();
var items = [];
• 如果你不知道數組長度,使用Array#push。
var someStack = [];
someStack[someStack.length] = 'abracadabra';
someStack.push('abracadabra');
• 當你需要複制數組的時候,請使用Array#slice。
var len = items.length,
itemsCopy = [],
i;
for (i = 0; i < len; i++) {
itemsCopy[i] = items[i];
}
itemsCopy = items.slice();
Strings
• 對于字元串,我們使用單引号''。
var name = "Bob Parr";
var name = 'Bob Parr';
var fullName = "Bob " + this.lastName;
var fullName = 'Bob ' + this.lastName;
• 超過80個字元的字元串,我們使用串聯符号(\),讓字元串多行顯示。
• 注意:如果過度使用帶串聯符号的字元可能會影響到性能。
var errorMessage = 'This is a super long error that was thrown because of Batman. When you stop to think about how Batman had anything to do with this, you would get nowhere fast.';
var errorMessage = 'This is a super long error that \
was thrown because of Batman. \
When you stop to think about \
how Batman had anything to do \
with this, you would get nowhere \
fast.';
var errorMessage = 'This is a super long error that ' +
'was thrown because of Batman.' +
'When you stop to think about ' +
'how Batman had anything to do ' +
'with this, you would get nowhere ' +
'fast.';
• 當我們在程式設計的時候,需要拼接出一個字元串,我們可以使用Array#join 代替字元串連接配接。尤其是對IE浏覽器。
var items,
messages,
length, i;
messages = [{
state: 'success',
message: 'This one worked.'
},{
message: 'This one worked as well.'
state: 'error',
message: 'This one did not work.'
}];
length = messages.length;
function inbox(messages) {
items = '<ul>';
for (i = 0; i < length; i++) {
items += '<li>' + messages[i].message + '</li>';
}
return items + '</ul>';
items = [];
items[i] = messages[i].message;
return '<ul><li>' + items.join('</li><li>') + '</li></ul>';
Functions
• 函數表達式
// anonymous function expression
var anonymous = function() {
return true;
// named function expression
var named = function named() {
// immediately-invoked function expression (IIFE)
(function() {
console.log('Welcome to the Internet. Please follow me.');
})();
• 絕對不要在非函數塊(if,while)申明一個函數。我們可以把函數申明變成一個函數表達式。
if (currentUser) {
function test() {
console.log('Nope.');
var test = function test() {
console.log('Yup.');
};
• 絕對不要把一個參數命名為arguments,arguments參數是函數作用域内給出的一個特殊變量,如果你把參數命名為arguments,那麼這個參數就會覆寫它原有的特殊變量。
function nope(name, options, arguments) {
// ...stuff...
function yup(name, options, args) {
總結
這些很多是大家都比較清楚的,平時經常用,我隻是強調一下,讓大家再複習一下。