tam
tam

Reputation: 1583

what are the advantages and disadvantages of anonymous methods in 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?

Upvotes: 5

Views: 4346

Answers (1)

jfriend00
jfriend00

Reputation: 708166

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)

Upvotes: 4

Related Questions