DIV CSS 佈局教程網

為 JavaScript 型別動態增加方法:靜態方法與實例方法的兩種做法
編輯:關於JavaScript     

前提:型別函式也是函式

JavaScript 的內建型別函式(Number、String、Boolean、Array、Date、Object 等)都繼承自 Function.prototype。因此給 Function.prototype 增加方法,會同時作用到所有由它衍生的型別函式上。

做法一:為型別增加「靜態方法」

Function.prototype.addMethod=function(methodName,func){
  if(!this[methodName]){
    this[methodName]=func;  // 為型別增加方法,類似靜態方法。func 賦在型別上而非實例上
  }
  return this;              // this 綁定到呼叫者(型別函式),返回 this 可鏈式呼叫
}

Array.addMethod('testFun',function(){alert(this)});
// Array.testFun(); → function Array() {[native code]}

Object.addMethod('testFun',function(){alert(this)});
// Object.testFun(); → function Object() {[native code]}

Boolean.addMethod('testFun',function(){alert(this)});
// Boolean.testFun(); → function Boolean() {[native code]}

function CustomObject(name,value){
  this.name=name || 'CustomObject';
  this.value=value || 0;
  this.toString=function(){return '[name:'+this.name+',value:'+this.value+']'}
}

CustomObject.addMethod('testFun',function(){alert(this)});
CustomObject.testFun();
/* 印出整個函式本體:
function CustomObject(name, value) {
  this.name = name || "CustomObject";
  this.value = value || 0;
  this.toString = function () {return "[name:" + this.name + ",value:" + this.value + "]";};
}
*/

注意 alert(this) 印出的是函式本身,因為 this 指向型別函式。這正是「靜態方法」的行為——它屬於型別,不屬於任何實例。

所以若改用實例呼叫就會報錯:

var customObject=new CustomObject();
customObject.testFun(); // Error: customObject.testFun is not a function

做法二:為型別的「實例」增加方法

如果目標是讓所有實例都能用,就必須把方法綁到 prototype 上:

Function.prototype.addMethod=function(methodName,func){
  if(!this.prototype[methodName]){
    this.prototype[methodName]=func;  // 為原型增加方法,會影響該型別的所有實例
  }
  return this.prototype;              // 返回原型,可鏈式呼叫
}

Object.addMethod('testFun',function(){alert(this)});
// ({}).testFun();  → [object Object]

Number.addMethod('testFun',function(){alert(this)});
// (5).testFun();   → 5

String.addMethod('testFun',function(){alert(this)});
// 'test'.testFun(); → 'test'

Boolean.addMethod('testFun',function(){alert(this)});
// true.testFun();   → true

Array.addMethod('testFun',function(){alert(this)});
// (['a','b']).testFun(); → a,b

Date.addMethod('testFun',function(){alert(this)});
// new Date().testFun(); → Tue Dec 27 2011 11:20:58 GMT-0800 (Pacific Standard Time)

function CustomObject(name,value){
  this.name=name || 'CustomObject';
  this.value=value || 0;
  this.toString=function(){return '[name:'+this.name+',value:'+this.value+']'}
}
CustomObject.addMethod('testFun',function(){alert(this)});

var customObject=new CustomObject();
customObject.testFun(); // [name:CustomObject,value:0]

此時反過來用型別呼叫就會報錯:

Array.testFun();        // Error: Array.testFun is not a function
CustomObject.testFun(); // Error: CustomObject.testFun is not a function

兩者的差別,一句話說清

掛載位置this 指向呼叫方式
this[methodName](型別函式本身)型別函式Array.testFun()
this.prototype[methodName]實例物件[].testFun()

這套寫法今天的問題與正確做法

這是 ES5 之前的經典技巧,但它有三個明確的缺點,今天不該再用:

一、污染全域原型。 修改 Function.prototype 會讓所有函式都多出 addMethod 屬性,而且預設是可列舉的,會干擾 for-in 遍歷(參見第 12994 篇)。

二、if 判斷會靜默失敗。 if(!this[methodName]) 這種寫法,遇到同名方法已存在時會悄悄跳過,除錯時很難察覺。而且它也擋不住「不同實作但同名」的情況。

三、return this.prototype 破壞鏈式語意。 第一版回傳 this(型別),第二版回傳 this.prototype,兩者混用時很容易搞混自己在操作什麼。

正確做法是用 ES6 class 的 static 與實例方法,語意清楚且不必動任何全域物件:

class CustomObject {
  // 靜態方法:用 CustomObject.create() 呼叫
  static create(name, value) {
    return new CustomObject(name, value);
  }

  // 靜態方法:用 CustomObject.testFun() 呼叫
  static testFun() {
    console.log(this);   // this 指向 CustomObject 本身
    return this;
  }

  constructor(name, value) {
    this.name = name || 'CustomObject';
    this.value = value || 0;
  }

  // 實例方法:用 obj.toString() 呼叫
  toString() {
    return `[name:${this.name},value:${this.value}]`;
  }
}

CustomObject.testFun();              // [class CustomObject]
const obj = CustomObject.create('a', 1);
obj.toString();                      // '[name:a,value:1]'

若真的需要給內建型別擴充(例如補 polyfill),請用 Object.defineProperty 並把 enumerable 設為 false,同時先做能力檢查:

if (!Array.prototype.myUnique) {
  Object.defineProperty(Array.prototype, 'myUnique', {
    value: function() { return [...new Set(this)]; },
    writable: true,
    configurable: true,
    enumerable: false        // 關鍵:不讓它出現在 for-in 中
  });
}

[1,1,2,3,3].myUnique(); // [1, 2, 3]

更好的選擇通常是寫成純函式(unique(arr))或放在工具物件裡(Utils.unique(arr)),完全不碰原型。

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