javascript - 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 ()
却没有)。
解决方案
您代码中的“div”showCircle(150, 150, 100).then(div => { } );
是从您的承诺函数 ShowCircle 返回的数据。通常,在箭头函数中,lambda 表达式 (=>) 左侧的任何内容都是函数的输入参数。
div => {
//doSomething here
}
是
function nameFunction(div){
//doSomething here
}
在 promise then的情况下,提供给函数的输入是 promise 的返回值。这里的参数被命名为 div 并保存 ShowCircle() 的返回值。
推荐阅读
- javascript - 将 Yii1 代码转换为 Yii2(更改语言部分)
- python - 错误:简单登录 GUI 的“分配函数调用的结果,其中函数没有返回”
- reactjs - 获取反应组件中的文本(单词)总数
- google-cloud-platform - 项目之间的“区域”是否不同?
- kotlin - 将图像加载到 RecyclerView 单元格中
- simulink - 在 Simulink 生成的代码中避免使用长整数(32 位)
- python - 如何在 Python 中的同一类中的方法中刷新实例变量列表?
- sql - 如何在 sqlite 中获得以秒为单位的时差?
- r - R - 如何正确运行 psych 包中的 testRetest 命令?
- r - 地图在其函数中无法识别 `.` 或 `.x`