Is there a difference between [removed] = stuff and [removed] = stuff()?

前端 未结 2 578
别跟我提以往
别跟我提以往 2021-01-25 19:45

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\");
         


        
相关标签:
2条回答
  • 2021-01-25 20:15

    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();
    
    0 讨论(0)
  • 2021-01-25 20:26

    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.

    0 讨论(0)
提交回复
热议问题