源码网商城,靠谱的源码在线交易网站 我的订单 购物车 帮助

源码网商城

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

  • 时间:2020-11-12 14:41 编辑: 来源: 阅读:
  • 扫一扫,手机访问
摘要:JavaScript中apply方法的应用技巧小结
[b]前言[/b] 最近在看JavaScript设计模式,其中有一些巧妙的函数。所以将部分修改后记录在此,顺便加上自己写出的一些好玩的函数。方便大家和自己以后使用。下面来一起看看。 [b]一、apply实现call[/b]
Function.prototype.call = function () {
 var ctx = [].shift.apply(arguments)
 return this.apply(ctx, arguments)
}
[b]二、apply实现bind[/b]
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)))
 }
}
[b]三、实现函数柯里化[/b]
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
严格模式不能使用[code]arguments.callee[/code], 稍微改一下
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
}
[b]四、实现函数反柯里化[/b]
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}
另一种方法:[code]call[/code]和[code]apply[/code]连用实现函数反柯里化
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]...)
 }
}
[b]五、为数组添加max函数[/b]
Array.prototype.max = function () {
 return Math.max.apply(null, this)
}
console.log([1, 3, 5, 2].max()) //5
[b]总结[/b] 以上就是这篇文章的全部内容改了,希望能对大家的学习和工作有所帮组,如果有疑问大家可以留言交流。
  • 全部评论(0)
联系客服
客服电话:
400-000-3129
微信版

扫一扫进微信版
返回顶部