gpt4 book ai didi

javascript - 避免在滚动上声明变量?

转载 作者:行者123 更新时间:2023-11-29 16:08:47 25 4
gpt4 key购买 nike

var variableOne;
var variableTwo;
var variableThree;

function veryInterestingFunction() {

var variableFour;

if(a){
variableFour = 'Good';
}
else {
variableFour = 'Decent';
}

console.log(variableFour);

}

$(window).on('scroll', function(){

veryInterestingFunction();

});

这里我在全局范围内有一些变量,一个函数声明一个变量并为其赋值,并在滚动时调用该函数。这样,您将在每个滚动条上声明“variableFour”,这不是一个好的做法,对吧?但是我不想用不必要的变量挤满全局范围并且也不能使用 IIFE。是否有一种“最佳实践”方法可以在函数外部声明变量并且仍然只能在该函数的范围内使用它?

http://jsfiddle.net/2jyddwwx/1/

最佳答案

to declare the variable outside the function and still only possible to use it inside the scope of that function ?

我想,那是不可能的

当我不想挤满全局范围时,我会声明一个全局对象,例如 App = {},而不是全局变量,我使用它的属性。

App.variableOne;
App.variableTwo;
App.variableThree;

或者你可以使用 ES6 中的类

关于javascript - 避免在滚动上声明变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34156709/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com