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

2022-01-11,,,,

这篇文章给大家总结了在js中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.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}

另一种方法:callapply连用实现函数反柯里化

 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

总结

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

以上就是JavaScript中apply方法的应用技巧小结的详细内容,更多请关注本站其它相关文章!

《JavaScript中apply方法的应用技巧小结.doc》

下载本文的Word格式文档,以方便收藏与打印。