What is the difference between including private functions in a jQuery plugin in the examples below:
Outside the loop:
(function( $ ){
var defaults = {};
$.fn.cmFlex = function(opts) {
this.each(function() {
var $this = $(this);
//Element specific options
var o = $.extend({}, defaults, opts);
//Code here
});
function f1(){....
function f3(){....
function f2(){....
};
})( jQuery );
Inside the loop:
(function( $ ){
var defaults = {};
$.fn.cmFlex = function(opts) {
this.each(function() {
var $this = $(this);
//Element specific options
var o = $.extend({}, defaults, opts);
function f1(){....
function f3(){....
function f2(){....
});
};
})( jQuery );
The advantage of including the functions in the loop is that i will be able to access the $this variable as well as the Element specific options from f1() f2() f3(), are there any disadvantages to this?
Always follow the concept of giving the least privilege to all your code. If no other code needs to reference those functions, there's no need to define them outside and changing those functions is simpler since you are guaranteed that they are not used anywhere else but within the loop.
If f1,f2,f3 needed access to closure variables within the looping function, they'd have to be defined in the function no matter what.
However there's a caveat. Defining them within a function requires creating a new closure every time the loop function is run. Depending on how tight the loop is, it could affect performance. My point is: premature optimization is bad, but keep it in mind.
FYI: Here's another way to do it (if you don't need the closure variables) that avoids creating the closures for every iteration of the loop. It looks a bit complex, so it's not for the faint of heart
(function( $ ){
var defaults = {};
$.fn.cmFlex = function(opts) {
this.each((function() {
function f1(){}
function f3(){}
function f2(){}
// This is the method that will be called for each iteration of the loop. It now
// has access to f1,f2,f3 but doesn't need to create a closure for each iteration.
return function() {
var $this = $(this);
//Element specific options
var o = $.extend({}, defaults, opts);
f1();
f2();
f3();
};
})());
};
})( jQuery );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With