Hakan
Hakan

Reputation: 3885

Difference between jquery functions and regular javascript functions?

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);
});

Upvotes: 2

Views: 717

Answers (2)

jkeesh
jkeesh

Reputation: 3339

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.

Upvotes: 0

Interrobang
Interrobang

Reputation: 17434

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.

Upvotes: 4

Related Questions