为什么这在箭头功能而不是常规功能中起作用?

时间:2019-07-21 20:19:24

标签: javascript

我想将窗口的宽度和高度值传递给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();

1 个答案:

答案 0 :(得分:-2)

原因是箭头函数是一个表达式,即它求值为一个值,而下面的函数是一个函数声明,这意味着它不求值,它是对一个未来值的引用调用该函数时将对其进行评估。

相关问题