1

I'm most familiar with Python and somewhat with C, and when I see this syntax in JS it really confuses me

function begin () {
    console.log("done did it");
}

window.onload = begin(); // the same output as
window.onload = begin;   // this one

In Python, one would be passing the return value of the function, the other a pointer to the function. What are the semantics in JS for these two statements?

Morgan Wilde
  • 16,795
  • 10
  • 53
  • 99

2 Answers2

10

Yes, there's a very big difference.

window.onload = stuff(); will call the stuff function and assign its return value to the onload property.

window.onload = stuff; assigns the stuff function to the property onload. The browser will call that function when the load event occurs. Functions are objects. When you refer to them by their name without calling them, you're referring to the object. This would be similar to the "function pointer" you were talking about.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
0

The right way is :

window.onload = xxxx;

the xxx must be a function.

the first one:

var fn = function() {
    alert("abc");
}

window.onload = fn;

the other one:

var fn = function() {
    var abc = "abc";
    return function () {
        alert(abc);
    }
}
window.onload = fn();
Andy12530
  • 9
  • 3