Objective
Recently looking at JavaScript design patterns, there are some ingenious functions. So take a partial change and record it here, plus some fun functions you've written. Convenient for everyone and their later use. Let's take a look together.
One, apply to achieve call
Function.prototype.call = function () {
var ctx = [].shift.apply (arguments) return
this.apply (CTX, arguments) c7/>}
Apply to achieve 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))]
}
}
Third, the realization function Corrie
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
}
}
//Usage
var add = function () {
var sum = 0 for
(var i = 0; i < a Rguments.length; i++) {
sum + = Arguments[i]
} return
sum
}.currying ()
Add (2)//No value
Add (3, 3)//not evaluated
Add (4)//Not evaluated
Console.log (Add ())//12
Strict mode can not be used arguments.callee , a little change
Function.prototype.currying = function () {
var args = [],
self = this
var f = function () {
if (argum Ents.length = = 0 {return
self.apply (this, args)
} else {
[].push.apply args, arguments] return
f
}
}
return F
}
Four, realize function inverse Corrie
Function.prototype.uncurrying = function () {
var self = This return
function () {
var obj = [].shift.apply (AR guments) return
self.apply (obj, arguments)
}
}
//usage
var push = Array.prototype.push.uncurrying (
var obj = {}
push (obj, ' Hey ')
console.log (obj)//{0: "Hey", length:1}
Another method: and used to call apply realize function anti-Corrie
Function.prototype.uncurrying = function () {
var self = ' return '
function () {return
Function.prototy Pe.call.apply (self, arguments)
//A bit around, is actually return Self.call (args[0), args[1], args[2] ...)
}
Add the Max function to an array
Array.prototype.max = function () {return
Math.max.apply (null, this)
}
Console.log ([1, 3, 5, 2].max ())/ /5
Summarize
The above is the entire content of this article changed, I hope to be able to learn and work for everyone to help group, if there are questions you can message exchange.