Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this how you define a function in jQuery?

Is this how you define a function in jQuery?

$(document).ready( function () {     var MyBlah = function($blah) { alert($blah);  };  }); 

Now to call the function I do:

MyBlah('hello'); 
like image 567
Blankman Avatar asked May 25 '09 18:05

Blankman


2 Answers

First of all, your code works and that's a valid way of creating a function in JavaScript (jQuery aside), but because you are declaring a function inside another function (an anonymous one in this case) "MyBlah" will not be accessible from the global scope.

Here's an example:

$(document).ready( function () {      var MyBlah = function($blah) { alert($blah);  };      MyBlah("Hello this works") // Inside the anonymous function we are cool.   });  MyBlah("Oops") //This throws a JavaScript error (MyBlah is not a function) 

This is (sometimes) a desirable behavior since we do not pollute the global namespace, so if your function does not need to be called from other part of your code, this is the way to go.

Declaring it outside the anonymous function places it in the global namespace, and it's accessible from everywhere.

Lastly, the $ at the beginning of the variable name is not needed, and sometimes used as a jQuery convention when the variable is an instance of the jQuery object itself (not necessarily in this case).

Maybe what you need is creating a jQuery plugin, this is very very easy and useful as well since it will allow you to do something like this:

$('div#message').myBlah("hello") 

See also: http://www.re-cycledair.com/creating-jquery-plugins

like image 64
Pablo Fernandez Avatar answered Oct 23 '22 03:10

Pablo Fernandez


No, you can just write the function as:

$(document).ready(function() {     MyBlah("hello"); });  function MyBlah(blah) {     alert(blah); } 

This calls the function MyBlah on content ready.

like image 35
gehsekky Avatar answered Oct 23 '22 04:10

gehsekky