JavaScript中apply方法的应用技巧小结

最近在看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

总结

以上就是这篇文章的全部内容改了,希望能对大家的学习和工作有所帮组,如果有疑问大家可以留言交流。

您可能感兴趣的文章:

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wzjwfw.html