国产探花免费观看_亚洲丰满少妇自慰呻吟_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

總結

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

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 青田县| 宁南县| 平远县| 金堂县| 南和县| 东阿县| 汝南县| 沈丘县| 巴彦淖尔市| 雅江县| 大安市| 张掖市| 九江市| 格尔木市| 南部县| 黎城县| 封开县| 肥西县| 景谷| 马尔康县| 仲巴县| 无为县| 福泉市| 元朗区| 酉阳| 射阳县| 疏附县| 兴国县| 周口市| 萍乡市| 洛隆县| 稻城县| 精河县| 博客| 博客| 利川市| 许昌市| 勃利县| 四平市| 进贤县| 睢宁县|