JavaScript中的ArrowFunction无法正常工作,为什么?但正常功能正常

时间:2019-06-04 07:48:51

标签: javascript html arrow-functions

这是简单的代码,单击该按钮后,我将尝试更改背景颜色

const colorBtn = document.querySelector('.colorBtn');
const bodyBcg = document.querySelector('body');
const colors = ['red', 'blue', 'yellow', 'green'];

colorBtn.addEventListener('click', changeColor);

    // const changeColor = () => {
    //     let random = Math.floor(Math.random() * colors.length);
    //     bodyBcg.style.background = colors[random];
    // };

function changeColor() {
    console.log('color change event');
    let random = Math.floor(Math.random() * colors.length);
    bodyBcg.style.background = colors[random];
}
body {
    display: flex;
    min-height: 100vh;
    justify-content: center;
    align-items: center;
}

.colorBtn {
    padding: 0.25rem 0.5rem;
    border: 10px;
    background-color: gray;
    color: white;
    outline: none;
    cursor: pointer;
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Hex Colors</title>
    <link rel="stylesheet" href="./main.css">
</head>
<body>
    <button type="button" class="colorBtn">Click here to change color</button>
    <script type="text/javascript" src="./script.js"></script>
</body>
</html>

但是当我们尝试使用名为changeColor的箭头功能时,它不起作用: 无法理解其背后的概念。

const changeColor = () => {
let random = Math.floor(Math.random() * colors.length);
bodyBcg.style.background = colors[random];
};

同样,它在chrome浏览器中也可以正常工作,但是当我尝试将调试点放在有效的changeColor函数上时, 引发错误:

const colorBtn = document.querySelector('.colorBtn');
ReferenceError: document is not defined

2 个答案:

答案 0 :(得分:3)

它不起作用,因为要将变量的功能链接到事件侦听器时,您的changeColor变量为undefined

只需在附加事件监听器之前对其进行定义。

const colorBtn = document.querySelector('.colorBtn');
const bodyBcg = document.querySelector('body');
const colors = ['red', 'blue', 'yellow', 'green'];

const changeColor = () => {
  let random = Math.floor(Math.random() * colors.length);
  bodyBcg.style.background = colors[random];
};

colorBtn.addEventListener('click', changeColor);
body {
    display: flex;
    min-height: 100vh;
    justify-content: center;
    align-items: center;
}

.colorBtn {
    padding: 0.25rem 0.5rem;
    border: 10px;
    background-color: gray;
    color: white;
    outline: none;
    cursor: pointer;
}
<button type="button" class="colorBtn">Click here to change color</button>


请注意:在这种情况下,changeColor是包含匿名函数变量

请查看@Duc Hong's answer,以获取有关起吊的说明。

答案 1 :(得分:2)

您遇到的问题称为hoisting。 JavaScript使用两种主要方法定义函数:函数声明(有时称为函数语句)和函数表达式。

函数声明:

function fncName() {}

函数表达式:

const x = function fncName(){}

这两种方法之间的主要功能差异是悬挂了函数声明,这意味着您甚至可以在定义函数之前调用它。函数表达式未悬挂。

在您的情况下,箭头函数是“函数表达式”,因此:

const x = () => {}

等同于:

const x = function fncName(){}

据我所知,使用箭头功能有两个原因:minimal syntaxlexical this

请注意Arrow functions on Mozzila site

中的这一点
  

箭头函数表达式在语法上是常规函数表达式的紧凑选择,尽管没有自身绑定到 this 自变量 super new.target 关键字。