【发布时间】:2020-01-12 01:47:18
【问题描述】:
我想知道是否可以将一组变量从全局范围移动到嵌套范围。在以下情况下是否可以使用闭包来实现这一点?应该是吧?
let 变量可能不应该在renderInfo() 范围内,因为renderInfo() 在加载时被多次调用,这是无法避免的。每次调用renderInfo() 时,render() 都会渲染多个元素,所有元素都添加了一个click 事件监听器。因此,变量也不能以代码当前的结构方式出现。
我尝试将clickToSort() 变成闭包,但每次都会遇到问题。我不知道如何允许所有带有click 事件侦听器的元素共享 访问let 变量。
let
sortNameAscending =
sortFreeAscending =
sortSizeAscending = true
// Called multiple times at load.
function renderInfo(a,b,c,d) {
// Renders multiple elements, and adds an event listener to them, each call.
function render(){
// The event listener is added to multiple elements
// that are also rendered herein.
ele.addEventListener('click', (e)=>clickToSort(e, cls, 'aString'))
}
// This function is added to the click event of tons of elements.
function clickToSort(e, cls, dataProperty) {
// How do I move the let variables from the global
// scope to here, so that they behave as if they
// are in the global scope? Is it possible with a
// closure?
// let
// sortNameAscending =
// sortFreeAscending =
// sortSizeAscending = true
// I imagine the following code should be wrapped in
// its own scope, but the scope must have access to
// the arguments of clickToSort(), and the let variables
// which should behave as if they are global.
if (cls.includes('whatever')) {
sortNameAscending = !sortNameAscending
} else if (cls.includes('whatever2')) {
sortFreeAscending = !sortFreeAscending
} else {
sortSizeAscending = !sortSizeAscending
}
}
}
我已经尝试了以下方法,但它不想工作。
let
sortNameAscending =
sortFreeAscending =
sortSizeAscending = true
function renderInfo(a,b,c,d) {
function render(){
// The event listener is added to multiple elements
// that are also rendered herein.
ele.addEventListener('click', (e)=>clickToSort(e, cls, 'aString'))
}
function clickToSort(e, cls, dataProperty) {
let
sortNameAscending =
sortFreeAscending =
sortSizeAscending = true
;(function whatevs(){
if (cls.includes('whatever')) {
sortNameAscending = !sortNameAscending
} else if (cls.includes('whatever2')) {
sortFreeAscending = !sortFreeAscending
} else {
sortSizeAscending = !sortSizeAscending
}
)()
}
}
我不确定为什么,尽管这可能与我将 clickToSort() 函数绑定到元素而不是返回函数这一事实有关?
【问题讨论】:
标签: javascript variables scope closures global-variables