DIV CSS 佈局教程網

用柯裡化思路手寫 bind:從原理到相容性處理
編輯:關於JavaScript     

先說柯裡化函數的思想

柯裡化可以視為一種「提前準備」的 JavaScript 手法。函數一旦被執行,就會產生一個暫時不會被釋放的作用域;我們把需要預先處理的內容存進這個作用域,然後回傳一個小函數。此後真正被呼叫的都是這個小函數,它可以直接把先前存好的值拿出來參與運算。也就是說,柯裡化承擔的是預處理的角色。

bind 要解決的問題

bind 的作用是把傳入的 callback 裡的 this,提前指向我們指定的上下文 context。

第一種寫法:通用的 bind 函數

 /**
 * bind 實現原理(寫法一)
 * @param callback [Function] 回調函數
 * @param context [Object] 上下文
 * @returns {Function} 改變 this 指向的函數
 */
function bind(callback, context) {
  var outerArg = Array.prototype.slice.call(arguments, 2); // 取出 callback、context 之後的其餘參數
  return function () {
    var innerArg = Array.prototype.slice.call(arguments, 0); // 取出呼叫時傳入的參數
    callback.apply(context, outerArg.concat(innerArg));
  };
}

這裡的關鍵在於兩次參數收集:外層先把「呼叫 bind 時多給的參數」存進閉包,內層再收集「實際呼叫時的參數」,最後用 concat 合併後一起 apply 給原函數,於是 this 指向與參數預填一次到位。

第二種寫法:擴充 Function.prototype

 /**
 * 模仿原型鏈上的 bind 實現(柯裡化函數思想)
 * @param context [Object] 上下文
 * @returns {Function} 改變 this 指向的函數
 */
Function.prototype.mybind = function mybind(context) {
  var _this = this;
  var outArg = Array.prototype.slice.call(arguments, 1);
  // 環境本身支援 bind 時,直接轉呼叫原生實作
  if ('bind' in Function.prototype) {
    return this.bind.apply(this, [context].concat(outArg));
  }
  // 不支援時自行拼裝
  return function () {
    var inArg = Array.prototype.slice.call(arguments, 0);
    inArg.length === 0 ? inArg[inArg.length] = window.event : null;
    var arg = outArg.concat(inArg);
    _this.apply(context, arg);
  };
};

兩個版本的核心完全一致,差別只在於第二版多做了一層能力偵測:有原生 bind 就借用,沒有才走自己的實作,這是處理相容性問題時相當實用的習慣。

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