重新调用IIFE

时间:2019-04-28 19:18:30

标签: javascript iife

为什么该代码块会引发错误“未捕获的ReferenceError:未定义setSize”

const canvas = document.querySelector("#draw");

(function setSize() {
    canvas.width = window.innerWidth;
    canvas.height = window.innerHeight;
})();

window.addEventListener("resize", () => {
    setSize();
})

1 个答案:

答案 0 :(得分:3)

只需定义您的setSize函数并调用一次即可(它的作用与IFFE相同)。

const canvas = document.querySelector("#draw");

function setSize() {
    canvas.width = window.innerWidth;
    canvas.height = window.innerHeight;
}

setSize();

window.addEventListener("resize", () => {
    setSize();
})