Last active
March 14, 2016 21:42
-
-
Save kimmobrunfeldt/ca53975d4ae9a7851fa9 to your computer and use it in GitHub Desktop.
JavaScript's arguments object is useful. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions_and_function_scope/arguments
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Example of creating wrapper function using `arguments` | |
function add(a, b) { | |
return a + b; | |
} | |
// Example call: | |
// > verboseAdd(1, 2); | |
// Calculating 1 + 2 | |
// < 3 | |
function verboseAdd(/* arguments */) { | |
// Convert arguments to real Array. | |
// arguments is similar to Array but lacks some properties | |
var args = Array.prototype.slice.call(arguments); | |
console.log('Calculating', args.join(' + ')); | |
// Call add function with arguments which were given to verboseAdd function | |
return add.apply(this, arguments); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Real life example of how to create wrapper for jQuery's ajax function | |
// Works exactly like jQuery's Ajax function except it logs some details of the request | |
function ajax(/* arguments */) { | |
// Do stuff before actual ajax call | |
console.log('About to call ajax'); | |
var ajaxPromise = $.ajax.apply(this, arguments); | |
// Do stuff after actual ajax call | |
ajaxPromise.done(function() { | |
console.log('Ajax call finished successfully'); | |
}).fail(function() { | |
console.log('Ajax call failed'); | |
}); | |
return ajaxPromise; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment