简体   繁体   中英

What is the difference between assigning a variable value with functionName() and just functionName?

const heightOutput = document.querySelector('#height');
const widthOutput = document.querySelector('#width');

function reportWindowSize() {
  heightOutput.textContent = window.innerHeight;
  widthOutput.textContent = window.innerWidth;
}

window.onresize = reportWindowSize;

why not window.onresize = reportWindowSize() ? it's function call, I want to trigger it. but when I add the () it's not working.

When you have the statement as reportWindowSize() , what this does is it invokes the function reportWindowSize . After the invocation, it returns some value which in this case is undefined . So, window.onresize will be assigned value undefined .

Now, let's talk about window.onresize . It is an event handler that gets triggered when certain events occur, in this case when window size is changed. More on events: Events API .

What this means is, when a window is resized some native code will call the handler window.onresize like this window.onresize() . If it is undefined then it won't work. It must be a function, so we either pass a reference of a function to it, which is exactly what you are doing or pass function value. Passing reference won't call the function but instead point it to the function you are passing. And finally, when the event is triggered the function reportWindowSize gets called.

Some resources that might be helpful:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM