国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > JavaScript > 正文

JavaScript中apply方法的應用技巧小結

2019-11-20 08:51:02
字體:
來源:轉載
供稿:網友

前言

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

另一種方法: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

總結

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

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 长武县| 茂名市| 阿城市| 卓资县| 秦皇岛市| 黎城县| 寻乌县| 郎溪县| 扎赉特旗| 闸北区| 田林县| 定襄县| 曲沃县| 万荣县| 建瓯市| 莲花县| 湛江市| 礼泉县| 巫山县| 广南县| 改则县| 雷波县| 醴陵市| 宜阳县| 石景山区| 思南县| 东安县| 海兴县| 湖口县| 琼中| 甘谷县| 微山县| 岳普湖县| 如皋市| 三门峡市| 贵港市| 招远市| 故城县| 兴山县| 封开县| 甘德县|