DIV CSS 佈局教程網

JavaScript 基礎知識精選(二):Cookie、正則表達式與 call/apply
編輯:JavaScript基礎知識     

本篇整理了幾個實用上非常關鍵的 JavaScript 技巧,包含 Cookie 操作、物件檢視、正則表達式,以及 call 與 apply 的應用。

一、Cookie 操作工具函式

以下封裝同時支援寫入與讀取 Cookie:

/**
 * Cookie 操作工具。
 * 用法:寫入 → CookieTool('name','1',{expires: 7}) // 儲存鍵為 name、值為 1,7 天後失效
 *      讀取 → CookieTool('name') // 回傳 1
 */
CookieTool = function(name, value, options) {
  if (typeof value != 'undefined') {
    options = options || {};
    if (value === null) { value = ''; options.expires = -1; }
    var expires = '';
    if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
      var date;
      if (typeof options.expires == 'number') {
        date = new Date();
        date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
      } else { date = options.expires; }
      expires = '; expires=' + date.toUTCString();
    }
    var path = options.path ? '; path=' + options.path : '';
    var domain = options.domain ? '; domain=' + options.domain : '';
    var secure = options.secure ? '; secure' : '';
    document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
  } else {
    var cookieValue = null;
    if (document.cookie && document.cookie != '') {
      var cookies = document.cookie.split(';');
      for (var i = 0; i < cookies.length; i++) {
        var cookie = trim(cookies[i]);
        if (cookie.substring(0, name.length + 1) == (name + '=')) {
          cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
          break;
        }
      }
    }
    return cookieValue;
  }
};

二、檢視 JS 物件內容的除錯函式

/** 用來查看一個物件的所有屬性 */
function debugObjectInfo(obj){
  traceObject(obj);
  function traceObject(obj){
    var str = '';
    if(obj.tagName && obj.name && obj.id)
      str = "<table border='1' width='100%'><tr><td colspan='2' bgcolor='#ffff99'>traceObject tag: <"+obj.tagName+"> name = \""+obj.name+"\" id = \""+obj.id+"\" </td></tr>";
    else
      str = "<table border='1' width='100%'>";
    var key = [];
    for(var i in obj){ key.push(i); }
    key.sort();
    for(var i = 0; i < key.length; i++){
      var v = new String(obj[key[i]]).replace(/</g,"<").replace(/>/g,">");
      str += "<tr><td valign='top'>"+key[i]+"</td><td>"+v+"</td></tr>";
    }
    str = str + "</table>";
    writeMsg(str);
  }
  function writeMsg(s){
    traceWin = window.open("", "traceWindow", "height=600, width=800,scrollbars=yes");
    traceWin.document.write(s);
  }
}

三、正則表達式速查

修飾符:g 全域比對、m 多行比對、i 忽略大小寫。

常用符號:^ 開頭、$ 結尾、*(0 次以上)、+(1 次以上)、?(0 或 1 次,跟在限制符後代表非貪婪模式)。字元類別:\d 數字、\D 非數字、\w 單字字元、\W 非單字字元、\s 空白、\S 非空白、\b 單字邊界、\B 非單字邊界。

四、call() 方法

語法:call([thisObj[, arg1[, arg2[, ...]]]])。第一個參數是被當作 this 的物件,後續則是要傳入的參數。call 可以借用另一個物件來呼叫方法,把函式的執行上下文從原本物件切換成指定的物件。

function add(a,b){ alert(a+b); }
function sub(a,b){ alert(a-b); }
add.call(sub, 3, 1); // 等同 add(3,1),結果 alert(4)

// 借用方法
function Class1(){ this.name = "class1"; this.showNam = function(){ alert(this.name); } }
function Class2(){ this.name = "class2"; }
var c1 = new Class1();
var c2 = new Class2();
c1.showNam.call(c2); // 用 c2 執行 c1 的方法,結果 alert("class2")

// 多重「繼承」
function Class10(){ this.showSub = function(a,b){ alert(a-b); } }
function Class11(){ this.showAdd = function(a,b){ alert(a+b); } }
function Class2(){ Class10.call(this); Class11.call(this); }

五、apply 方法

Function.apply(obj, args) 接收兩個參數:obj 用來取代 this,args 則是作為參數傳入的陣列。它與 call 效果類似,差別在於 apply 的參數以陣列形式傳遞。

function Person(name, age){
  this.name = name; this.age = age;
  this.sayhello = function(){ alert("hello"); };
}
function Student(name, age, grade, school){
  Person.apply(this, arguments);
  this.grade = grade; this.school = school;
}
var s1 = new Student("tom", 13, 6, "清華小學");
s1.sayhello();

// 用 apply 求陣列最大值
function getMax2(arr){ return Math.max.apply(null, arr); }

// 用 apply 合併陣列
Array.prototype.push.apply(arr1, arr2);
XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved