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。是否有一种“最佳实践”方法可以在函数外部声明变量并且仍然只能在该函数的范围内使用它?
最佳答案
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/