DIV CSS 佈局教程網

JavaScript 常用程式碼片段整理(10 則)
編輯:關於JavaScript     

以下彙整十則日常開發中反覆用到的程式碼片段,涵蓋資料轉換、時間處理、跨視窗溝通與原型繼承等主題,可作為隨手查閱的小抄。

1. JSON 轉字串

function json2str(o) {
  var arr = [];
  var fmt = function (s) {
    if (typeof s == 'object' && s != null) return json2str(s);
    return /^(string|number)$/.test(typeof s) ? "'" + s + "'" : s;
  };
  for (var i in o) arr.push("'" + i + "':" + fmt(o[i]));
  return '{' + arr.join(',') + '}';
}

若只是想把物件序列化,JSON.stringify 是標準答案;上面這種手寫版本適合用來生成 SQL 片段或自訂格式的字串。

2. 時間戳轉 Date

function fromUnixTime(timeStamp) {
  if (!timeStamp || timeStamp < 1000 || timeStamp == ' ') return "";
  var theDate = new Date(parseInt(timeStamp) * 1000);
  return theDate;
}

關鍵是 Unix 時間戳以「秒」為單位,而 JavaScript 的 Date 建構子要的是「毫秒」,因此必須乘以 1000。

3. Date 格式化擴充

// 作者: meizz 
// 對 Date 的擴展,將 Date 轉化為指定格式的 String  
// 月(M)、日(d)、小時(h)、分(m)、秒(s)、季度(q) 可以用 1-2 個占位符,  
// 年(y)可以用 1-4 個占位符,毫秒(S)只能用 1 個占位符(是 1-3 位的數字)  
// 例子:  
// (new Date()).Format("yyyy-MM-dd hh:mm:ss.S") ==> 2012-12-02 08:12:04.423  
// (new Date()).Format("yyyy-M-d h:m:s.S")      ==> 2012-12-02 8:12:4.18  
 Date.prototype.Format = function(fmt) { 
   var o = {
     "M+": this.getMonth() + 1,                    //月份   
     "d+": this.getDate(),                     //日   
     "h+": this.getHours(),                   //小時   
     "m+": this.getMinutes(),                 //分  
     "s+": this.getSeconds(),                 //秒  
     "q+": Math.floor((this.getMonth() + 3) / 3), //季度  
     "S": this.getMilliseconds()                    //毫秒  
   };
   if (/(y+)/.test(fmt))
     fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
   for (var k in o)
     if (new RegExp("(" + k + ")").test(fmt))
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
   return fmt;
};

這版的優點是用「佔位符長度」自動決定是否補零,寫法比逐段 replace 更緊湊。

4. 日期加 n 天

function addDay(number) {
       return fromUnixTime(new Date().getTime() / 1000 + 24 * 60 * 60 * number);
 }

5. iframe 父子視窗互相呼叫

// 父窗體調用子窗體內的函數 
 window.frames['ifm_id'].valueChange("id_101"); 
 // 子窗體調用父窗體的函數 
 parent.refreshTree("nodeId_202"); 

6. 彈出視窗與回傳值

// 彈出窗體 
 var url = "https://www.baidu.com"; 
 win=window.showModalDialog(url,window,"dialogLeft:400;dialogTop:200;dialogWidth:560px;dialogHeight:380px;scroll:yes;menubar:no;toolbar:no;status:no;"); 
 // 在彈出窗體中設置返回值 
 var result = new Array(); 
 result[0] = "id_101"; 
 result[1] = "name_202"; 
 window.returnValue = result; 
 window.close(); 

showModalDialog 屬 Gecko 私有實作,Chrome 已於 2014 年移除支援,新專案請改用 <dialog> 元素或自行以 CSS 遮罩實作。

7. 作用域:只有全域與函式作用域

// 1. 全局作用域 
 var id = "global variable";   // 1.1 在函數外部定義的變量  
 function showMsg(){     
  message = "global message";// 1.2 未定義而直接賦值的變量  
                              //     在第一次使用時被定義為全局變量  
 } 
 // 2. 函數作用域 
 function doCheck(){ 
  var data = "function data"; // 2.1 在函數內部定義的變量 
 } 

ES5 之前 JavaScript 沒有區塊作用域,迴圈或 if 區塊內以 var 宣告的變數會外洩;ES6 的 let / const 才補上了這塊。而函式內未宣告就賦值的變數會成為全域變數,這在嚴格模式下會直接拋錯,建議一律開啟 'use strict'。

8. 三種繼承機制

// 1. 對象冒充繼承  
 function Person(strName){ 
  // private fields 
  var name = strName; 
  // public methods 
  this.getName = function(){ 
    return name; 
  };     
 } 
 function Student(strName,strSchool){ 
  // 定義父類的屬性及方法    
  this.parent = Person; 
  this.parent(strName); 
  delete this.parent;      // 刪除臨時變量 parent 
  // 定義新屬性及方法    
  // private fields 
  var school = strSchool; 
  // public methods 
  this.getSchool = function(){ 
    return school; 
  };     
 } 
 // 2. Funtion 對象的 call(..) 或 apply(..) 繼承  
 //   call 和 apply 的區別在於:  
 //     call  的第二個參數為可變參數;  
 //     apply 的第二個參數為 Array;  
 function Animal(strName,intAge){ 
  // private fields 
  var name = strName; 
  var age = intAge; 
  // public methods 
  this.getName = function(){ 
    return name; 
  };  
  this.getAge = function(){ 
    return age; 
  }; 
 } 
 function Cat(strName,intAge,strColor){ 
  // 定義父類的屬性及方法    
  Animal.call(this,strName,intAge); 
  // Animal.apply(this,new Array(strName,intAge)); 
  // 定義新屬性及方法    
  // private fields 
  var color = strColor; 
  // public methods 
  this.getInfo = function(){ 
    return "name:" + this.getName() + "\n" 
          + "age:" + this.getAge() + "\n" 
          + "color:" + color; 
  }; 
 } 
 // 3. prototype 繼承  
 //   prototype 聲明的屬性及方法被所有對象共享  
 //   prototype 只有在讀屬性的時候會用到  
 Function.prototype.extend = function(superClass){ 
  // 此處的 F 是為了避免子類訪問父類中的屬性 this.xxx 
  function F(){}; 
  F.prototype = superClass.prototype; 
  // 父類構造函數 
  this.superConstructor = superClass; 
  this.superClass = superClass.prototype; 
  this.prototype = new F(); 
  this.prototype.constructor = this; 
 }; 
 Function.prototype.mixin = function(props){     
  for (var p in props){         
    this.prototype[p] = props[p];         
  } 
 }; 
 function Box(){} 
 Box.prototype = {     
  getText : function(){ 
    return this.text; 
  }, 
  setText : function(text){ 
    this.text = text; 
  } 
 }; 
 function CheckBox(){} 
 CheckBox.extend(Box); 
 CheckBox.mixin({ 
  isChecked : function(){ 
    return this.checked; 
  }, 
  setChecked : function(checked){ 
    this.checked = checked; 
  } 
 }); 

這裡的 extend 用了「空函式 F 做中介」的技巧,避免呼叫父類建構函式而產生多餘的 this 屬性,是相當經典的寫法。若環境允許,ES6 的 class / extends 能以更直觀的語法表達同一件事。

9. call、apply 與 bind

// thisArg 表示在 fun 內部時 this 所指示的對象 
 // call & apply 將立即執行 fun 並返回結果 
 var result = fun.call(thisArg,arg1,...); 
 var result = fun.apply(thisArg,[argsArray]); 
 // thisArg 表示在 fun 內部時 this 所指示的對象 
 // bind 返回的是一個匿名函數 
 var tmpfun = fun.bind(thisArg); 
 var result = tmpfun(arg1,...); 
<script type="text/javascript"> 
/** 
 * 擴展 Function 的功能 
 */ 
 Function.prototype.bind = function(obj){ 
  var method = this; 
  var tmpfun = function(){ 
    return method.apply(obj,arguments); 
  }; 
  return tmpfun; 
 } 
 function Parent(){ 
  this.name = "parent"; 
 } 
 function Child(){ 
  this.name = "child"; 
  this.getName = function(time){ 
    return time + " " + this.name; 
  }; 
 } 
 var parent = new Parent(); 
 var child = new Child(); 
 alert(child.getName(1));                  // show 1 child 
 alert(child.getName.call(parent,2));  // show 2 parent [call & apply 會立即執行] 
 var tmpfun = child.getName.bind(parent);// bind 不會立即執行 
 alert(tmpfun(3));                          // show 3 parent 
 </script> 

三者最直觀的差別:call 與 apply 立刻執行並回傳結果,差別只在參數傳遞形式;bind 則回傳一個 this 已被綁定的新函式,執行時機交由呼叫端決定。ES5 已內建 bind,上述手寫版本僅為理解原理之用。

10. == 運算子的轉換規則

轉換規則 
  如果一個操作數是 Boolean 值,則比較之前將其轉成數字:false -> 0, true -> 1; 
  如果一個操作數是數字,另一操作數是字符串,則比較之前將字符串轉成數字; 
  如果一個操作數是對象,另一操作數是數字或字符串,則比較之前會將對象轉為基本類型, 
     引擎會先嘗試調用 valueOf(),如果 valueOf() 沒有 override 或返回一個對象, 
     則引擎會嘗試調用 toString(),如果 toString() 沒有 override 或返回一個對象,則拋出異常; 
  如果是兩個對象進行比較,則判斷它們是否引用同一對象; 
  如果一個操作數是 NaN, == 將返回 false, != 將返回 true; 
  null 和 undefined 與其它值比較將返回 false, 
     但 null == null, undefined == undefined, null == undefined; 
  參與比較時 null 和 undefined 不能轉為其它值;   

這些隱式轉換正是無數 bug 的來源,因此實務上的一致建議是:比較時一律使用 ===,把型別判斷的主導權交回給自己。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved