重溫 Javascript:The Definitive Guide 的筆記

##此筆記按時間逆序排序 !!

ECMAScript 5 普及前 for in 的使用注意事項

for(p in o) {
    if (!o.hasOwnProperty(p)) continue; // 跳過繼承的屬性
}
for(p in o) {
    if (typeof o[p] === 'function') continue; // 跳過方法
}

建立新對象

var o1 = Object.create(Object.prototype);
var o1 = {};
var o1 = new Object();
兩者都繼承自Object

若是不繼承任何東西
var o1 = Object.create(null);

對象繼承函數

// 一致認爲 Douglas Crockford 是最先提出用這種方法實現對象繼函數的人
function inherit(p) {
    if (p == null) throw TypeError();
    if (Object.create())
        return Object.create(p);
    var t = typeof p;
    if (t !== "object" %% t !== "function")
        throw TypeError();
    function f() {};
    f.prototype = p;
    return new f();
}

with 語句

example: document.forms[0].address.value = "";

      -> with(document.forms[0]) {
             address.value = "";
         }

Error

throw new Error("error message");

for in 循環只遍歷 「可枚舉」 屬性

var 聲明的變量是沒法經過 delete 刪除的

in 運算符 incetanceos 運算符

顯式類型轉換

Number類tostring()方法,能夠接受表示轉換基數(radix)的可選參數
toFixed()根據小數點後指定位數將數字轉換爲字符串
toExponential()使用指數記數法將數字轉換爲指數形式字符串
parseInt(string, [radix]) parseFloat()

引用類型

對象( 引用類型 reference type )
對象的比較均是引用的比較

良好習慣從我作起-定義全局Global

var global = this; // 客戶端裏由 window 代替

判斷NaN

x != x     結果爲true    x 爲 NaN
isNaN(x)   結果爲true    x 爲 NaN 或非數字值

經常使用Math對象屬性

Math.pow(2, 53) // 2的53次冪
Math.round(.6) // 四捨五入
Math.ceil(.6) // 向上求整
Math.floor(.6) // 向下求整
Math.abs(-5) // 求絕對值
Math.max(x, y, z) // 返回最大值
Math.min(x, y, z) // 返回最小值
Math.random() // 生成一個大於等於0小於1.0的僞隨機數
Math.PI // 圓周率
Math.E // 天然對數的底數
Math.sqrt(3) // 3的平方根
Math.pow(3, 1/3) // 3的立方根
Math.sin(0) // 三角函數,還有Math.cos,Math.atan等
Math.log(10) // 10的天然對數
Math.log(100)/Math.LN10 // 以10爲底100的對數
Math.log(512)/Math.LN2 // 以2爲底512的對數
Math.exp(3) // e的三次冪

Debug Logger

function debug(msg) {
    var log = document.getElementById("debuglog");

    if (!log) {
        log = document.createElement("div");
        log.id = "debuglog";
        log.innerHTML = "<h1>Debug Log</h1>";
        document.body.appendChild(log);
    }

    var pre = document.createElement("pre");
    var text = document.createTextNode(msg);
    pre.appendChild(text);
    log.appendChild(pre);
}
相關文章
相關標籤/搜索