DIV CSS 佈局教程網

JavaScript 中 apply 方法的應用技巧彙總
編輯:關於JavaScript     

前言

近來在看 JavaScript 設計模式,其中有不少巧妙的函式。於是我把部分內容整理修改後記錄下來,順帶寫上一些自己覺得好玩的函式,方便大家以後查閱使用。下面一起來看看。

一、用 apply 實現 call

 Function.prototype.call = function () { var ctx = [].shift.apply(arguments) return this.apply(ctx, arguments) }

二、用 apply 實現 bind

 Function.prototype.bind = function () { var ctx = [].shift.apply(arguments), args = [].slice.apply(arguments), self = this return function () { return self.apply(ctx, args.concat([].slice.apply(arguments))) } }

三、實現函式柯裡化

 Function.prototype.currying = function () { var args = [], self = this return function () { if (arguments.length === 0) { return self.apply(this, args) } else { [].push.apply(args, arguments) return arguments.callee } } } //用法 var add = function () { var sum = 0 for (var i = 0; i < arguments.length; i++) { sum += arguments[i] } return sum }.currying() add(2) //並未求值 add(3, 3) //並未求值 add(4) //並未求值 console.log(add()) //12

嚴格模式下不能使用 arguments.callee,稍微改一下即可:

 Function.prototype.currying = function () { var args = [], self = this var f = function () { if (arguments.length === 0) { return self.apply(this, args) } else { [].push.apply(args, arguments) return f } } return f }

四、實現函式反柯裡化

 Function.prototype.uncurrying = function () { var self = this return function () { var obj = [].shift.apply(arguments) return self.apply(obj, arguments) } } // 用法 var push = Array.prototype.push.uncurrying() var obj = {} push(obj, '嘿') console.log(obj) //{0: "嘿", length: 1}

另一種做法:把 call 和 apply 連用來實現反柯裡化。

 Function.prototype.uncurrying = function () { var self = this return function () { return Function.prototype.call.apply(self, arguments) //有點繞,其實就是return self.call(args[0], args[1], args[2]...) } }

五、為陣列添加 max 函式

 Array.prototype.max = function () { return Math.max.apply(null, this) } console.log([1, 3, 5, 2].max()) //5

總結

這些技巧的共同核心,都在於靈活運用 apply 來動態指定 this 與傳入陣列參數。把 call、apply 玩透,很多看似複雜的函式高階用法都能自己實現出來。希望本文能對你的學習與工作有所幫助,若有疑問歡迎留言交流。

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