Javascript 箭头函数中的参数名称
Parameter names in Javascript arrow functions
我正在阅读 Javascript 的 Promise 类型,但我对 .then(...)
中 div 的用途感到困惑
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 中 return 编辑的数据。通常,在箭头函数中,lambda 表达式 (=>) 左侧的任何内容都是该函数的输入参数。
div => {
//doSomething here
}
是
function nameFunction(div){
//doSomething here
}
在 promise then 情况下,提供给函数的输入是来自 promise 的 return 值。这里的参数命名为 div 并保存来自 ShowCircle() 的 return 值。
我正在阅读 Javascript 的 Promise 类型,但我对 .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 中 return 编辑的数据。通常,在箭头函数中,lambda 表达式 (=>) 左侧的任何内容都是该函数的输入参数。
div => {
//doSomething here
}
是
function nameFunction(div){
//doSomething here
}
在 promise then 情况下,提供给函数的输入是来自 promise 的 return 值。这里的参数命名为 div 并保存来自 ShowCircle() 的 return 值。