locked
Why can't functions declared as variables be attached as event listeners?

    Question

  • So for example, I have:

    button.addEventListener('click',fxnName,false);

    if the function is declared as

    var fxnName = function(){

    ...

    }

    it won't get executed, whereas it will be called if it is declared like this:

    function fxnName(){

    ...

    }

    Sunday, November 10, 2013 7:51 AM

Answers

  • Hi Jd Dantes,

    Good Question, this is often asked in JavaScript, Take a look at a hot discussion from StackOverFlow: http://stackoverflow.com/questions/336859/var-functionname-function-vs-function-functionname

    The difference is that "var fxnName = function(){...}" is defined at run-time, whereas "function fxnName(){...}" is defined at parse-time for a script block. "addEventListener" is a kind of delegate, in your code, the function will be called when the mouse click event fires. That's why you could only use "function fxnName(){...}".

    Best Regards,

    --James


    <THE CONTENT IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, WHETHER EXPRESS OR IMPLIED>
    Thanks
    MSDN Community Support

    Please remember to "Mark as Answer" the responses that resolved your issue. It is a common way to recognize those who have helped you, and makes it easier for other visitors to find the resolution later.

    • Marked as answer by Jd Dantes Monday, November 11, 2013 2:22 PM
    Monday, November 11, 2013 5:26 AM
    Moderator