更好的 JavaScript 寫法筆記

parseInt() 的第二個參數

// 建議指定第二個參數
> parseInt("123", 10)
123
> parseInt("010", 10)
10
// 如果不指定,以下的 "010" 將會被改為 8 進位,因為最前方的 0 
> parseInt("010")
8

雙等號運算子 ==(等於)會進行型態強制轉換

> "monkey" == "monkey"
true
> 1 == true
true
// 避免型態強制轉換,要用三等號運算子
> 1 === true
false
> true === true
true

while 迴圈以及 do-while 迴圈的不同

while (true) {
  // 無限迴圈!
}

do {
  // 執行至少一次,僅管條件不符合 while(false)
} while (true)

&& 以及 || 運算子「短路邏輯」檢查

// 存取一個物件的屬性前檢查物件是否為空 (null)
// 第一 o 不為空才會存取 getName() 屬性
var name = o && o.getName();

// 用來設預設值:
// 如果 otherName 為空,name 就會被設為"預設"
var name = otherName || "預設";

三元運算子 (tertiary operator)

var allowed = (age > 18) ? "是" : "否";

建立空物件的兩種基本方法

var obj = new Object();
// 以及
var obj = {};

物件屬性的兩種存取方法

obj.name = "小明"
var name = obj.name;
// 以及
obj["name"] = "小明";
var name = obj["name"];

更有效率的陣列查詢 -> 避免每迴圈一次就會查詢一次 length 屬性

// 正常方式
for (var i = 0; i < arr.length; i++) {
    //處理 arr[i]
}
// 避免每迴圈一次就會查詢一次 length 屬性,以下方式較有效率
for (var i = 0, len = arr.length; i < len; i++) {
    //處理 arr[i]
}

函式裡的參數 arguments

// 存取一個叫做 arguments 的變數,一個類似陣列的物件,內含所有遞給函式的值
function avg() {
    var sum = 0;
    for (var i = 0, j = arguments.length; i < j; i++) {
        sum += arguments[i];
    }
    return sum / arguments.length;
}
> avg(2, 3, 4, 5)
3.5

apply() 與 call()

基本上的不同在於傳入參數的方式, call() 是以逗號分開的參數, apply() 是以傳入一個陣列的方式。

fun.apply(thisArg, [argsArray])

fun.call(thisArg, arg1, arg2,...)

巢狀函式

將只有該函式會使用到的函式包括在其中。這樣便能保持全域領域 (global scope) 的函式不會太多。不在全域領界內塞太多函式是件好事情。

function betterExampleNeeded() {
    var a = 1;
    function oneMoreThanA() {
        return a + 1;
    }
    return oneMoreThanA();
}

Closures(閉包) 避免 memory leak 破壞相互參照(circular reference)的方法

// 將物件 el 直接設為 null
function addHandler() {
    var el = document.getElementById('el');
    el.onclick = function() {
        this.style.backgroundColor = 'red';
    }
    el = null;
}
// 藉由增加一個新的 closure 來解除 circular reference
function addHandler() {
    var clickHandler = function() {
        this.style.backgroundColor = 'red';
    }
    (function() {
        var el = document.getElementById('el');
        el.onclick = clickHandler;
    })();
}
// 直接避開 closure
var el = document.getElementById('el');
el.onclick = clickHandler;

var clickHandler = function() {
    this.style.backgroundColor = 'red';
}

 

整理自:https://developer.mozilla.org/zh-TW/docs/Web/JavaScript/A_re-introduction_to_JavaScript