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?
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With