2

What't the point of writing jquery functions like this:

(function( $ ) {
  $.fn.simple_hide_function = function() {
  var $t = this;
  $t.hide();
  };
})( jQuery );

$(window).load(function () {
$('#myId').simple_hide_function();
});

Why not do it like this:

function simple_hide_function(id){
id.hide();
};

$(window).load(function () {
var my_id = $('#my_id');
simple_hide_function(my_id);
});

Added question:

Would it be any problem doing this?

function simple_hide_function(id){
id.hide();
};

$(window).load(function () {
var my_id1 = $('#my_id1'),
my_id2 = $('#my_id2'),
my_id3 = $('#my_id3');
simple_hide_function(my_id1);
simple_hide_function(my_id2);
simple_hide_function(my_id3);
});
1
  • 2
    For the added question: if you don't mind that your code is hard to read, reuse and maintain, why not. It is called "bad practice". As you become a better and better developer, you will realize how you just cannot do things like that. Commented Dec 29, 2011 at 10:54

2 Answers 2

4

In the plugin version, you are creating a new function and attaching it to the jQuery object. By making your function a member of the object, you can take advantage of things like jQuery's chaining, where multiple functions are invoked on the same object in a row.

In the second version, you are creating a function in the global scope and passing it a jQuery object. This pollutes the global namespace (now your function is visible everywhere) and it just doesn't really fall in line with the jQuery philosophy.

However, as you've found, there are no functional differences. Both will execute fine.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks Interrobang, I think I understand what you mean. Just to make shore, there is nothing wrong doing like the secound version?
Well, with your second version, you can't do $('#my_id1, #my_id2, #my_id3').simple_hide_function(); like you can with the plugin version. If you are going to be operating on things with jQuery, you should definitely use a jQuery plugin, that's the whole point of them.
0

I think the main idea is that you are not cluttering up the global namespace. In your second example simple_hide_function belongs to the window, and could possibly cause a name conflict, but in the first example it is a local variable.

2 Comments

thanks jkeesh! I added a question. Would this "clutter up" anything?
The second example also clutters the global namespace since simple_hide_function is stil bound to the window. Parts of the answer above explain the other benefits of using jQuery plugins.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.