Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what are the advantages and disadvantages of anonymous methods in javascript?

Tags:

javascript

in javascript there are so many different ways to set up a method for something such as a button click event.

for example say you have retreived an input element 'button'

function MyForm(){
   //anonymous method
   button.click = function(){ //work };


   //private method
   var handleClick = function () { // work };
   button.click = handleClick;

   //public method
   button.click = outerClickHandle;


}

//public
function outerClickHandle(){
    // work
}

//prototype
MyForm.prototype.outerClickProto(){
   //work
}

there are of course some of the more obvious answers such as encapsulation when desired. And with the prototype you don't have to recreate that function each time which is good for performance, but as for anonymous methods, other than being a nice way, or flow of writing the script, what is good and bad?

like image 678
tam Avatar asked Oct 09 '22 19:10

tam


1 Answers

The main advantage I find is that because it's declared inline, the anonymous function has access to all the current local variables within scope which can vastly simplify your code in some circumstances. A classic example is with setTimeout() where you want it to operate using variables defined in the scope above.

Of course, an anonymous function also doesn't interfere with whatever namespace you're in (global, local within the function, etc...) since it doesn't need a name.

A disadvantage of using an anonymous function with an addEventListener(type, fn) event handler is that you can't remove just that event listener because you don't have a handle on the function.

Another disadvantage of anonymous functions is that a new function is created every time the code that uses it runs, which in some cases makes no difference at all, but in other cases may be something to consider for performance reasons (e.g., if doing things in a loop)

like image 130
jfriend00 Avatar answered Oct 13 '22 05:10

jfriend00