简体   繁体   English

如何避免在 javascript 滑块中使用全局变量

[英]How to avoid using global variables in javascript slider

Bear with me as I am still learning javascript.请耐心等待,因为我仍在学习 javascript。 I have created a simple slider that moves left and right on click.我创建了一个简单的滑块,可以在单击时左右移动。 It uses the transform property and moves it 25% in the desired direction.它使用变换属性并将其向所需方向移动 25%。

What I want to do is get into the habit of not using global variables for simple things like this.我想要做的是养成不将全局变量用于这样简单的事情的习惯。 Below is what I have and it works fine but would appreciate any advice on cleaning it up a little.以下是我所拥有的,它运行良好,但希望能得到任何有关清理它的建议。

var wildlifeSlideLeft = document.querySelector('.wildlife__btn--previous');
var wildlifeSlideRight = document.querySelector('.wildlife__btn--next');
var wildlifeSlider = document.querySelector('.wildlife__images__slider');
var wildlifeCurrentPosition = 0

//Wildlife slide left
wildlifeSlideLeft.addEventListener('click', function () {
    slideLeft();
});

//Wildlife slide right
wildlifeSlideRight.addEventListener('click', function () {
    slideRight();
});

function slideLeft() {
    if(!(wildlifeCurrentPosition === 0)) {
        wildlifeCurrentPosition = wildlifeCurrentPosition + 25;
        wildlifeSlider.style.transform = "translateX(" + wildlifeCurrentPosition + "%)";
    }
}

function slideRight() {
    if(!(wildlifeCurrentPosition === -100)) {
        wildlifeCurrentPosition = wildlifeCurrentPosition - 25;
        wildlifeSlider.style.transform = "translateX(" + wildlifeCurrentPosition + "%)";
    }   
}

The simplest approach (minimal code change) would be to wrap your code in an anonymous closure.最简单的方法(最少的代码更改)是将您的代码包装在匿名闭包中。

Ie: IE:

(function (){

    //Your code goes here.

})();

This keeps those variable within the scope of the closure rather than attaching them to global scope.这将这些变量保持在闭包的范围内,而不是将它们附加到全局范围内。

Or for even more readability and maybe even testability.或者为了更多的可读性,甚至可能是可测试性。 You could name the function and invoke it.您可以命名该函数并调用它。

function attachSliderEvents() {
    //Your code goes here.
}

attachSliderEvents();

If all you want to do is keep the variables out of window , you could use an IIFE .如果您只想将变量保留在window ,则可以使用IIFE

(function () {
  let wildlifeSlideLeft = document.querySelector('.wildlife__btn--previous');
  let wildlifeSlideRight = document.querySelector('.wildlife__btn--next');
  let wildlifeSlider = document.querySelector('.wildlife__images__slider');
  let wildlifeCurrentPosition = 0;

  // Wildlife slide left
  wildlifeSlideLeft.addEventListener('click', function () {
    slideLeft();
  });

  // Wildlife slide right
  wildlifeSlideRight.addEventListener('click', function () {
    slideRight();
  });

  function slideLeft () {
    if (!(wildlifeCurrentPosition === 0)) {
      wildlifeCurrentPosition = wildlifeCurrentPosition + 25;
      wildlifeSlider.style.transform = 'translateX(' + wildlifeCurrentPosition + '%)';
    }
  }

  function slideRight () {
    if (!(wildlifeCurrentPosition === -100)) {
      wildlifeCurrentPosition = wildlifeCurrentPosition - 25;
      wildlifeSlider.style.transform = 'translateX(' + wildlifeCurrentPosition + '%)';
    }
  }
})();

Answer回答

You could use a Self-Executing Anonymous Function to wrap everything related to your Slider in a variable named Slider .您可以使用自执行匿名函数将与您的 Slider 相关的所有内容包装在名为Slider的变量中。

Working Example:工作示例:

 var Person = (function(){ var personName = 'Johnny'; var getName = () => personName; return { getName: getName } })(); console.log(Person.getName()); //Johnny

Further explanation进一步说明

This way, Person has its own Scope ( that contains variables, functions etc ) which you can access using a dot on your variable.这样, Person有自己的Scope (包含变量、函数等),您可以使用变量上的点访问它。 Eg.例如。 Slider.slideLeft()

A simple solution would be to wrap this in a self invoking anonymous function.一个简单的解决方案是将其包装在一个自调用匿名函数中。

(function() {
  //insert code here
})();

Then you can pass arguments such as the document to it.然后,您可以将诸如文档之类的参数传递给它。

(function(d){
    var wildlifeSlideLeft = d.querySelector('.wildlife__btn--previous');
    //...
 })(document);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM