如何将这段使用箭头函数的JavaScript代码转换为普通函数?
转换为普通函数版本的代码
下面是把你提供的箭头函数替换为普通函数后的代码:
const arrows = document.querySelectorAll(".arrow"); const movieLists = document.querySelectorAll(".movie-list"); arrows.forEach(function(arrow, i) { const itemNumber = movieLists[i].querySelectorAll("img").length; let clickCounter = 0; arrow.addEventListener("click", function() { const ratio = Math.floor(window.innerWidth / 270); clickCounter++; if (itemNumber - (4 + clickCounter) + (4 - ratio) >= 0) { movieLists[i].style.transform = `translateX(${movieLists[i].computedStyleMap().get("transform")[0].x.value - 300}px)`; } else { movieLists[i].style.transform = "translateX(0)"; clickCounter = 0; } }); });
替换说明:
- 将
arrows.forEach((arrow, i) => {})中的箭头函数替换为function(arrow, i) {} - 将
addEventListener的箭头回调() => {}替换为function() {}
由于原代码中没有依赖箭头函数的this绑定特性(这里使用的是外部作用域的i、itemNumber等变量),所以直接替换为普通函数即可正常运行。
内容的提问来源于stack exchange,提问作者Hanishkaran Muneswaran
相关产品推荐
相关产品推荐

