DIV CSS 佈局教程網

JavaScript 方法重寫與高階函式應用
編輯:關於JavaScript     

以下內容整理自《JavaScript 語言精粹》中關於方法化的技巧,示範如何替型別動態掛上方法、以及如何呼叫被改寫掉的原方法。

// 為 Function 的 prototype 加上 method 方法,讓所有函式都能動態擴充
Function.prototype.method = function (name, fn) {
  this.prototype[name] = fn;   // this 指的就是 Function.prototype
  return this;                 // 回傳自身,支援 jQuery 式的串接操作
};

// Number 是建構函式,因此擁有 method 方法;呼叫後回傳 Number 本身
Number.method("integer", function () {});
(10 / 3).integer();

// 保存原方法以便日後呼叫(類似 super)
Object.method("superior", function (name) {
  var that = this;
  var method = that[name];          // 先把原方法存起來
  return function () {
    return method.apply(that, arguments);   // 用 apply 保住 this 指向
  };
});

關鍵是 apply 與 that

最後那段是整篇最重要的技巧。當子類改寫了父類的方法,往往還需要在新方法中呼叫舊方法。做法是:先把原函式存進區域變數,回傳一個新的函式,新函式透過 apply(that, arguments) 呼叫舊函式。

這裡的 that = this 是必要步驟。如果直接寫 method.apply(this, arguments),回傳的新函式在被呼叫時 this 會變成全域物件(或 undefined),原本的方法就取不到物件自身的屬性了。

一個應用示例

var coolcat = function (spec) {
  var that = cat(spec);                       // 先取得基礎物件
  var getName = that.superior("getName");     // 保留原始的 getName
  that.getName = function () {
    return "me" + getName() + "me";           // 在新方法中呼叫舊方法
  };
  return that;
};

這個模式的效果等同於類別繼承中的 super 呼叫。在 ES6 之後,直接用 class 與 super 關鍵字就能表達同樣的意圖,語意清楚得多:

class CoolCat extends Cat {
  getName() {
    return "me" + super.getName() + "me";
  }
}

關於 Function.prototype.method 的提醒

這個技巧示範了「函式也是物件、可以掛方法」這個核心觀念,但擴充內建原型在真實專案裡要謹慎:可能與其他函式庫命名衝突,而且新增的可列舉屬性會出現在 for-in 走訪中。現代的替代方案是直接定義獨立工具函式,或用 ES Module 匯出。

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