首页 > 解决方案 > Javascript 箭头函数中的参数名称

问题描述

我正在阅读 Javascript 的 Promise 类型,但我对 div 中的用途感到困惑.then(...)

function go() {
  showCircle(150, 150, 100).then(div => {
    div.classList.add('message-ball');
    div.append("Hello, world!");
  });
}

function showCircle(cx, cy, radius) {
  let div = document.createElement('div');
  div.style.width = 0;
  div.style.height = 0;
  div.style.left = cx + 'px';
  div.style.top = cy + 'px';
  div.className = 'circle';
  document.body.append(div);

  return new Promise(resolve => {
    setTimeout(() => {
      div.style.width = radius * 2 + 'px';
      div.style.height = radius * 2 + 'px';

      div.addEventListener('transitionend', function handler() {
        div.removeEventListener('transitionend', handler);
        resolve(div);
      });
    }, 0);
  })
}
.message-ball {
  font-size: 20px;
  line-height: 200px;
  text-align: center;
}
.circle {
  transition-property: width, height, margin-left, margin-top;
  transition-duration: 2s;
  position: fixed;
  transform: translateX(-50%) translateY(-50%);
  background-color: red;
  border-radius: 50%;
}
<button onclick="go()">Click me</button>

我想了解“div”的意义(尽管我尝试重命名它,并且.then(...)工作正常,但匿名function ()却没有)。

标签: javascriptlambdapromisearrow-functions

解决方案


您代码中的“div”showCircle(150, 150, 100).then(div => { } );是从您的承诺函数 ShowCircle 返回的数据。通常,在箭头函数中,lambda 表达式 (=>) 左侧的任何内容都是函数的输入参数。

div => {
//doSomething here
}

function nameFunction(div){
//doSomething here
    }

在 promise then的情况下,提供给函数的输入是 promise 的返回值。这里的参数被命名为 div 并保存 ShowCircle() 的返回值。


推荐阅读