最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

JavaScript中apply方法的應(yīng)用技巧小結(jié)

 更新時間:2016年09月29日 09:55:26   投稿:daisy  
這篇文章給大家總結(jié)了在js中apply方法的一些應(yīng)用技巧,通過這些技巧對大家日常的使用相信會有幫助,有需要的朋友們下面來一起看看吧。

前言

最近在看JavaScript設(shè)計模式,其中有一些巧妙的函數(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}

另一種方法:callapply連用實(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é)

以上就是這篇文章的全部內(nèi)容改了,希望能對大家的學(xué)習(xí)和工作有所幫組,如果有疑問大家可以留言交流。

相關(guān)文章

最新評論

额尔古纳市| 宣恩县| 崇义县| 白河县| 南昌县| 顺平县| 博罗县| 平乡县| 栾川县| 民和| 高淳县| 东莞市| 临澧县| 靖安县| 界首市| 宁强县| 井冈山市| 比如县| 中牟县| 前郭尔| 澳门| 增城市| 竹北市| 房山区| 卓尼县| 七台河市| 昌乐县| 闽清县| 抚顺市| 伊宁市| 合肥市| 石家庄市| 黎城县| 金川县| 哈尔滨市| 万安县| 石柱| 滁州市| 浪卡子县| 桂东县| 左云县|