-3

I have made 3 functions on calling the windowScroll function. Why does it not work with the extra parenthesis, but works when inside its own function or without parenthesis?

var windowScroll = function() {
    var doesNotRun = function() {
        console.log('does not run');
    };
    var doesRun = function() {
        console.log('does run');
    };
    window.onscroll = doesNotRun();
    window.onscroll = doesRun;
    window.addEventListener('scroll', function(){
        doesRun();
    });
};
windowScroll();

Here is a link on codepen: http://codepen.io/marcoangelo/pen/KWdWem

Any help to understand why Javascript does this would be great.

vinS
  • 1,417
  • 5
  • 24
  • 37
Marco Angelo
  • 79
  • 1
  • 8
  • 1
    In the first case you actually calling the new function created by *bind*, which doesn't have a return statement so you're setting *window.onscroll* to undefined. In strict mode, *this* will be undefined too (not that it matters in this case since whatever is passed to the function is not used). – RobG Feb 28 '17 at 13:12
  • 2
    I don't see why the massive downvoting is neccessary, this is a legit question. A little odd, but legit. Not everyone is a programming guru – Evochrome Feb 28 '17 at 13:13
  • thanks for the replies. I realise its not a decoration Denys, I am trying to understand why the language behaves like this. To me, I would have thought the doesNotRun function should work even without .bind(this) but it doesn't. – Marco Angelo Feb 28 '17 at 13:57

1 Answers1

2

You need to assign a function object to the event handler properties.

doesRun and doesNotRun are expressions that resolve to function objects.

doesRun() and doesNotRun() are expressions that (immediately) call those functions and resolve to the return value you get when you call them. In this case, since the functions do not have return statements, that is undefined.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335