DIV CSS 佈局教程網

JavaScript 建立函數的 20 種寫法整理
編輯:JavaScript綜合知識     

日常開發中,建立函數的方式其實遠比大多數人以為的多。本文把+function 宣告、函數表達式、物件方法、原型鏈到鏈式呼叫等常見寫法逐一列出,方便對照理解彼此的差異。

1. 函數宣告

function sayHello(){ console.log('hello'); }
function leave(){ console.log('goodbye'); }
sayHello();

最直覺的寫法,遇到需求先宣告一個具名函數。

2. 函數表達式

var sayHello = function(){ console.log('hello'); }
var leave = function(){ console.log('goodbye'); }
leave();

把函數當值指派給變數,可避免污染全域的函數宣告。

3. 物件字面量包一層

var Action = {
  sayHello : function(){ console.log('hello'); },
  leave : function(){ console.log('goodbye'); }
}
Action.sayHello();

把相關方法收在同一個命名空間下,結構看起來整齊得多。

4. 為單體掛上屬性

var Action = function(){};
Action.sayHello = function(){ console.log('hello'); }
Action.leave = function(){ console.log('goodbye'); }
Action.sayHello();

5. 建構式回傳新物件

var Action = function(){
  return {
    sayHello : function(){ console.log('hello'); },
    leave : function(){ console.log('goodbye'); }
  }
}
var a = Action();
a.leave();

回傳一個全新物件,後續能做的變化更多。

6. 原型鏈掛方法

var Action = function(){};
Action.prototype.sayHello = function(){ console.log('hello'); }
Action.prototype.leave = function(){ console.log('goodbye'); }
var a = new Action();
a.sayHello();

方法只建立一次,所有實例共用,避免重複配置。

7. 整包指派給 prototype

var Action = function(){};
Action.prototype = {
  sayHello : function(){ console.log('hello'); },
  leave : function(){ console.log('goodbye'); }
}
var a = new Action();
a.leave();

8. 在建構式內部用 this

var Action = function(){
  this.sayHello = function(){ console.log('hello'); }
  this.leave = function(){ console.log('goodbye'); }
}
var a = new Action();
a.leave();

每個實例各自擁有一份方法,彈性但較耗記憶體。

9. 直接擴充 Function 原型

Function.prototype.sayHello = function(){ console.log('hello'); }
Function.prototype.leave = function(){ console.log('leave'); }
var f = function(){};
f.sayHello();

等於替所有函數開了一塊新空間,威力大但副作用也大,正式專案要謹慎。

10~13. addMethod 家族:從單參數到鏈式

// 單一函數掛在函數物件上
Function.prototype.addMethod = function(name, fn){ this[name] = fn; }
var methods = function(){};
methods.addMethod('sayHello', function(){ console.log('hello'); });
methods.addMethod('leave', function(){ console.log('leave'); });
methods.sayHello();

// 改成掛到 prototype 上,供 new 出來的實例使用
Function.prototype.addMethod = function(name, fn){ this.prototype[name] = fn; }
var Methods = function(){};
Methods.addMethod('sayHello', function(){ console.log('hello'); });
var a = new Methods();
a.leave();

// 加上 return this,就能鏈式呼叫
Function.prototype.addMethod = function(name, fn){ this[name] = fn; return this; }
var methods = function(){};
methods.addMethod('sayHello', function(){ console.log('hello'); })
       .addMethod('leave', function(){ console.log('leave'); });
methods.leave();

14~17. 一次傳入整個物件

Function.prototype.addMethod = function(obj){
  for (var key in obj){ this[key] = obj[key]; }
}
var methods = function(){};
methods.addMethod({
  sayHello : function(){ console.log('hello'); },
  leave : function(){ console.log('goodbye'); }
});
methods.leave();

把 this[key] 換成 this.prototype[key] 就是類別式的版本;再加上 return this,鏈式呼叫同樣適用。

18~20. 加上型別判斷的通用版

Function.prototype.addMethod = function(){
  if (arguments.length < 1) return;
  var tostring = Object.prototype.toString;
  if (tostring.call(arguments[0]) === '[object Object]'){
    for (var key in arguments[0]){ this[key] = arguments[0][key]; }
  } else if (typeof arguments[0] === "string" &&
             tostring.call(arguments[1]) === '[object Function]'){
    this[arguments[0]] = arguments[1];
  }
  return this;
}

最後一版更進一步,用一個布林參數決定要掛到建構式本身還是它的 prototype 上:

Function.prototype.addMethod = function(){
  if (arguments.length < 1) return;
  var cout = 0, tostring = Object.prototype.toString, that;
  if (typeof arguments[0] === "boolean" && arguments[0]){
    cout++; that = this;
  } else {
    that = this.prototype;
  }
  if (tostring.call(arguments[cout]) === '[object Object]'){
    for (var key in arguments[cout]){ that[key] = arguments[cout][key]; }
  } else if (typeof arguments[cout] === "string" &&
             tostring.call(arguments[cout + 1]) === '[object Function]'){
    that[arguments[cout]] = arguments[cout + 1];
  }
  return this;
}

var Text1 = function(){};
Text1.addMethod('sayHello', function(){ console.log('last say hello!') })
     .addMethod('leave', function(){ console.log('last goodbye!') });
var t = new Text1();
t.sayHello();

var test2 = function(){};
test2.addMethod(true, 'sayHello', function(){ console.log('last say hello!') })
     .addMethod(true, 'leave', function(){ console.log('last goodbye!') });
test2.sayHello();

後記

這 20 種寫法其實環繞著三條主線:函數本身是不是建構式、方法掛在建構式還是它的 prototype、以及要不要支援鏈式呼叫。理解這三個維度,即使遇到沒見過的寫法也能快速判斷它在做什麼。另外要提醒的是,直接擴充 Function.prototype 這類做法雖然示範性很強,在多人協作的專案中容易造成非預期的副作用,建議只在隔離的模組內使用。

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