简体   繁体   English

为什么这适用于箭头函数,而不是常规函数?

[英]Why this works in arrow func, and not regular func?

I wanted to pass the width and height values of the window to the only canvas tag in html, and also keep pass the values whenever the window viewport is changed or changing.我想将窗口的宽度和高度值传递给 html 中唯一的画布标签,并在窗口视口更改或更改时保持传递值。

const canvas = document.querySelector('canvas');



//   Why does this work?
const getViewport = ()=> { 
    [canvas.width , canvas.height] = [window.innerWidth , window.innerHeight];
    console.log(canvas.width);
    console.log(canvas.height);
};


// Why this doesn't work?
function getViewport() {
    [canvas.width , canvas.height] = [window.innerWidth , window.innerHeight];
    console.log(canvas.width);
    console.log(canvas.height);
};

/* I used this with arrow function, tried this on regular function
and did't work so I tried below code */
window.onresize = getViewport;


/* This only runs on the first time when the window is loaded, and
does not run after when i change the window size */
window.onresize = getViewport();

原因是箭头函数是一个表达式,即它评估为一个值,而您下面的函数是一个函数声明,这意味着它不评估为一个值,它是一个引用,让我们说一个未来的值在调用函数时计算。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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