Summary of the application skills of the apply method in JavaScript and the apply Application Skills
Preface
Recently, I have been looking at the JavaScript design patterns, some of which are clever functions. Therefore, after some modifications are recorded here, some interesting functions written by myself are added. It is convenient for you to use it later. Let's take a look.
1. call using apply
Function.prototype.call = function () { var ctx = [].shift.apply(arguments) return this.apply(ctx, arguments)}
Ii. bind implementation with apply
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))) }}
Iii. Implement function kerialization
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 <arguments. length; I ++) {sum + = arguments [I]} return sum }. currying () add (2) // not evaluate add (3, 3) // not evaluate add (4) // not evaluate console. log (add () // 12
Strict mode is not availablearguments.callee
, Change it a bit
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}
Iv. Implement function anti-Keri
Function. prototype. uncurrying = function () {var self = this return function () {var obj = []. shift. apply (arguments) return self. apply (obj, arguments) }}// usage var push = Array. prototype. push. uncurrying () var obj = {} push (obj, 'Hi') console. log (obj) // {0: "Hey", length: 1}
Another method:call
Andapply
Used to implement function Inversion
Function. prototype. uncurrying = function () {var self = this return function () {return Function. prototype. call. apply (self, arguments) // It is actually a return self. call (args [0], args [1], args [2]...)}
5. Add a max function to the array
Array.prototype.max = function () { return Math.max.apply(null, this)}console.log([1, 3, 5, 2].max()) //5
Summary
The above is all the content of this article. I hope to help you learn and work. If you have any questions, please leave a message.