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

來源:互聯網
上載者:User

前言

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

strict 模式不能使用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

總結

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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.