-2

I have some experience with javascript already, but I have a doubt for quite a while: why can't you pass a named function to places where it is expected an anonymous function to execute a piece of code? ie:

document.getElementById('btn').addEventListener('click', function(){
    alert('Hello World');
});

Now let's say I already have a function that does this.

var func = function(){
    alert('Hello World');
}

Why it isn't executed as a callback to the click event?

 document.getElementById('btn').addEventListener('click', func);

it seems redundant to create a anonymous function to then call a named function:

 document.getElementById('btn').addEventListener('click', function(){
     func();
 });
XVirtusX
  • 679
  • 3
  • 11
  • 30
  • 3
    You **can** pass a named function, exactly as you describe. – Pointy Aug 06 '15 at 17:45
  • 3
    Your example isn't a named function and if it does not work it has nothing to do with the fact that you put it in a variable. – Kyll Aug 06 '15 at 17:45
  • whatever you have here, should work. I still am wondering what do u mean when you say, *it seems redundant to create a anonymous function to then call a named function:* – Sudhansu Choudhary Aug 06 '15 at 17:47
  • 1
    To put it another way, nothing "expects" an anonymous function; that doesn't make any sense in JavaScript. If something expects a function, it expects a function, and there's no difference in that context between one that happens to be anonymous and one that isn't. – Pointy Aug 06 '15 at 17:48
  • `document.getElementById('btn').addEventListener('click', func);` works without any problem... – Tyr Aug 06 '15 at 17:48
  • 1
    check your console for errors – scrappedcola Aug 06 '15 at 17:50
  • Could be use of var to declare your function. See http://stackoverflow.com/questions/336859/var-functionname-function-vs-function-functionname – laughingpine Aug 06 '15 at 17:55
  • @Pointy Wrong, there _is_ a difference. The API can check for the `name` property of the function. But that's a dumb thing to do. Like, double dumb... – Kyll Aug 06 '15 at 19:18
  • @Kyll fine, but that just tells it whether the function was defined with a name; it says nothing about whether the function was instantiated as part of the API call or instead was declared/defined elsewhere. Also, as you say, it's pointless :) – Pointy Aug 06 '15 at 20:00

1 Answers1

0

I'd have to take a look at your full code, but you CAN pass a function as a variable.

document.getElementById('button1').addEventListener('click', function(){
alert('Hello World');
});


var func = function(){
   alert('Hello World, it is me again.');
};

document.getElementById('button2').addEventListener('click', func);

Check out the fiddle here:

https://jsfiddle.net/b4ktmp09/

Could you possibly be declaring the variable for the function (func) in the wrong spot in your code, causing it to be null?

Kasey
  • 307
  • 1
  • 8