DIV CSS 佈局教程網

用柯裡化函數實現 bind 方法的原理詳解
編輯:關於JavaScript     

先理解柯裡化的思想

柯裡化函數本質上是一種「預先處理」的思想:利用函數執行後形成一個不會銷毀的作用域,把需要預先處理的內容都存進這個作用域,並返回一個小函數。此後我們執行的都是這個小函數,在它內部對之前存好的值進行相關操作即可。可以說,柯裡化函數主要起到預處理的作用。

而 bind 方法的作用,正是把傳入的 callback 回調函數中的 this 預先處理為指定的上下文 context。

實現原理一:獨立 bind 函數

 /** * bind方法實現原理1 * @param callback [Function] 回調函數 * @param context [Object] 上下文 * @returns {Function} 改變this指向的函數 */ function bind(callback,context) { var outerArg = Array.prototype.slice.call(arguments,2);// 表示取當前作用域中傳的參數中除了fn,context以外後面的參數; return function (){ var innerArg = Array.prototype.slice.call(arguments,0);//表示取當前作用域中所有的arguments參數; callback.apply(context,outerArg.concat(innerArg)); } }

實現原理二:掛在原型鏈上的 mybind

下面用柯裡化思想模擬掛在原型鏈上的 bind,並兼顧瀏覽器是否原生支持 bind 的情況:

 /** * 模仿在原型鏈上的bind實現原理(柯理化函數思想) * @param context [Object] 上下文 * @returns {Function} 改變this指向的函數 */ Function.prototype.mybind = function mybind (context) { var _this = this; var outArg = Array.prototype.slice.call(arguments,1); // 兼容情況下 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); } }

兩種實現的關鍵點都在於:先保存外部參數(outerArg / outArg),再在返回的小函數中收集調用時的參數(innerArg / inArg),最後合併並用 apply 綁定上下文執行。這正是柯裡化「預處理 + 延遲執行」思想的完美體現。

以上就是關於用柯裡化函數實現 bind 方法的全部內容,希望能給你帶來參考。

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