Monday, May 6, 2024
 Popular · Latest · Hot · Upcoming
46
rated 0 times [  48] [ 2]  / answers: 1 / hits: 164437  / 15 Years ago, mon, may 25, 2009, 12:00:00

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

More From » jquery

 Answers
123

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


[#99458] Wednesday, May 20, 2009, 15 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
emilee

Total Points: 365
Total Questions: 113
Total Answers: 109

Location: Monaco
Member since Fri, Sep 24, 2021
3 Years ago
;