Introduction
Choosing which way to declare a JavaScript function can be confusing for beginners as there are several different ways to declare functions using JavaScript/jQuery. I’ll try to explain the benefits of each one and how and why you might use them when writing your awesome jQuery code.
1. The basic JavaScript function
This is the simplest way to declare a function in JavaScript. Say for example, we want to write a simple function called multiply(x,y) which simply takes in two parameters x and y, does a simple x times y and returns the value. Here are a few ways you might go about doing exactly this.
function multiply(x,y) {
return (x * y);
}
console.log(multiply(2,2));
If you wanted a quick function to test something then maybe that’s the only occasion you would use this. It’s not good coding and doesn’t promote code reuse.
2. JavaScript functions for get/set
If you need a private utility for getting/setting/deleting model values then you can declare a function as a variable like this. This could be useful for assigning a variable upon declaration calculated by a function.
var multiply = function(x,y) {
return (x * y);
}
console.log(multiply(2,2));
var multiply = function(x,y) {
return (x * y);
}(2,2);
console.log(multiply);
3. Create your own jQuery function
This is an awesome way to declare functions that can be used just like your regular jQuery functions, on your DOM elements! Rememeber jQuery.fn is just an alias for jQuery.prototype (which just saves us time when coding such jQuery.fn.init.prototype = jQuery.fn = $.fn as such).
jQuery.fn.extend({
zigzag: function () {
var text = $(this).text();
var zigzagText = '';
var toggle = true;
$.each(text, function(i, nome) {
zigzagText += (toggle) ? nome.toUpperCase() : nome.toLowerCase();
toggle = (toggle) ? false : true;
});
return zigzagText;
}
});
console.log($('#tagline').zigzag());
console.log($('#tagline').zigzag().toLowerCase());
Don’t forget to return the element so that you can chain jQuery functions together.
4. Extend Existing jQuery Functions
(or which either extend existing jQuery functions with extra functionality or creating your own functions that can be called using the jQuery namespace (usually, we use the $ sign to represent the jQuery namespace). In this example the $.fn.each function has been modified with custom behaviour.
(function($){
var oldEachFn = $.fn.each;
$.fn.each = function() {
var ret = oldEachFn.apply(this, arguments);
try {
$(this).css({'background-color':'orange'});
var msg = 'Danger high voltage!';
$(this).prepend(msg);
}
catch(e)
{
console.log(e);
}
return ret;
}
})(jQuery);
5. Functions in custom namespaces
JQUERY4U = {
multiply: function(x,y) {
return (x * y);
}
}
JQUERY4U.multiply(2,2);
Conclusion
Knowing when and how to declare different types of JavaScript/jQuery functions is definitely something any good js developer should know inside out.
Read More »