前言
最近在看JavaScript設(shè)計(jì)模式,其中有一些巧妙的函數(shù)。所以將部分修改后記錄在此,順便加上自己寫出的一些好玩的函數(shù)。方便大家和自己以后使用。下面來一起看看。
一、apply實(shí)現(xiàn)call
Function.prototype.call = function () { var ctx = [].shift.apply(arguments) return this.apply(ctx, arguments)}二、apply實(shí)現(xiàn)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))) }}三、實(shí)現(xiàn)函數(shù)柯里化
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嚴(yán)格模式不能使用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}四、實(shí)現(xiàn)函數(shù)反柯里化
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連用實(shí)現(xiàn)函數(shù)反柯里化
Function.prototype.uncurrying = function () { var self = this return function () { return Function.prototype.call.apply(self, arguments) //有點(diǎn)繞,其實(shí)就是return self.call(args[0], args[1], args[2]...) }}五、為數(shù)組添加max函數(shù)
Array.prototype.max = function () { return Math.max.apply(null, this)}console.log([1, 3, 5, 2].max()) //5總結(jié)
以上就是這篇文章的全部?jī)?nèi)容改了,希望能對(duì)大家的學(xué)習(xí)和工作有所幫組,如果有疑問大家可以留言交流。
新聞熱點(diǎn)
疑難解答
圖片精選