문제

내가 겪고 있는 문제는 다른 요소에 대해 함수가 여러 번 호출될 때입니다.나는 이 함수가 여러 요소에 사용될 수 있도록 모든 변수를 지역화해야 한다고 생각합니다.중요한 경우에는 jquery 1.3도 호출합니다.

pageSlide를 한 번만 호출하면 문제가 없지만 여러 번 호출하면 고통스럽습니다.오류는 없고 단지 이상한 동작만 있을 뿐입니다.

코드가 업데이트되었습니다.

var slideMenu=function(){
  var speed, startWidth, time, menuId, liID, menuLen, menuWidth, globalWidth, openWidth;
  return{

    speed : 0, startWidth : 0, time  : 0, menuId  : 0, liID : 0, menuLen  : 0,        menuWidth  : 0, globalWidth : 0, openWidth : 0,

    build:function(ulID,passStartWidth,passTime,s,passSlideLen,passHeight){
      speed=s;
      startWidth=passStartWidth;
      time=passTime;
      menuId=document.getElementById(ulID);
      liID=menuId.getElementsByTagName('li');
      menuLen=liID.length;
      menuWidth=menuId.offsetWidth;
      globalWidth=menuWidth/menuLen;
      openWidth=Math.floor((menuWidth-startWidth)/(menuLen-1));
      var i=0;
      for(i;i<menuLen;i++){
        s=liID[i];
        s.style.width=globalWidth+'px';
        this.timer(s)
      }
      if(passSlideLen!=null){
        menuId.timer=setInterval(function(){
          slideMenu.slide(liID[passSlideLen-1])
        },time)
      }
    },
    timer:function(s){
      s.onmouseover=function(){
        clearInterval(menuId.htimer);
        clearInterval(menuId.timer);
        menuId.timer=setInterval(function(){
          slideMenu.slide(s)
        },
        time)
      }
      s.onmouseout=function(){
        clearInterval(menuId.timer);
        clearInterval(menuId.htimer);
        menuId.htimer=setInterval(function(){
          slideMenu.slide(s,true)
        },
        time)
      }
    },
    slide:function(s,passChange){
      var changeWidth=parseInt(s.style.width);
      if((changeWidth<startWidth && !passChange) || (changeWidth>globalWidth && passChange)){
        var overallWidth=0;
        var i=0;
        for(i;i<menuLen;i++){
          if(liID[i]!=s){
            var slideObj,openWidth; var opening=0; slideObj=liID[i]; openWidth=parseInt(slideObj.style.width);
            if(openWidth<globalWidth && passChange){
              opening=Math.floor((globalWidth-openWidth)/speed);
              opening=(opening>0)?opening:1;
              slideObj.style.width=(openWidth+opening)+'px';
            }else if(openWidth>openWidth && !passChange){
              opening=Math.floor((openWidth-openWidth)/speed);
              opening=(opening>0)?opening:1;
              slideObj.style.width=(openWidth-opening)+'px'
            }
            if(passChange){
              overallWidth=overallWidth+(openWidth+opening)}else{overallWidth=overallWidth+(openWidth-opening)
            }
          }
        }
        s.style.width=(menuWidth-overallWidth)+'px';
      }else{
        clearInterval(menuId.timer);
        clearInterval(menuId.htimer)
      }
    }
  };
}();

위의 코드는 오류는 아니지만 작동하지 않습니다.this 키워드를 사용해도 나아지지 않습니다.

내 질문은 어떤 변수가 "this"여야 하는지입니다.효과가 있을 것으로 생각되는 다양한 조합을 시도했지만 뭔가 빠졌습니다.

도움이 되었습니까?

해결책

모듈 패턴의 전반적인 개념을 오해하고 계신 것 같습니다. 모든 인스턴스 간에 전역 정적 변수를 공유해야 하는 경우 return 문 바로 앞에 "var" 키워드를 사용하여 변수를 선언하거나 초기화할 수 있습니다.

해당 변수를 변경할 때마다 모든 인스턴스가 변경의 영향을 받는다고 가정합니다..

var slideMenu=function(){
    // Declare or initialize your private static variables here    
    var speed, startWidth, time;

    return {
        // Public part of your object
        slide:function(s,passChange){
            //To access your variable        
            speed = 20;
        ...

반면 전역 범위에서 변수를 안전하게 유지하려면 함수에서 반환된 개체에 변수를 넣어야 합니다. 이는 다음을 제공하는 신뢰할 수 있는 방법입니다. 인스턴스별 고유 속성.

var slideMenu=function(){
    // Declare or initialize your private static variables here    
    var speed, startWidth, time;

    return {
        // Public part of your object
        // Declare internal or public properties here
        menuId  : 0, 
        liID    : 0, 
        menuLen : 0,
        ...
        slide:function(s,passChange){
            //To access your private static variable inside functions        
            speed = 20;
            // To access your public/internal properties
            this.menuId = s; // for example ;) 
        }

결론적으로

때때로 내부/공용 속성을 구별하는 데 도움을 주기 위해 일부 사람들은 내부 속성에 밑줄을 표시합니다(속성은 여전히 ​​외부에서 액세스할 수 있다는 점에 유의하세요).

도움이 되길 바랍니다. 행운을 빕니다!

다른 팁

객체에서 개인 정적 변수를 보유 할 수있는 모듈 패턴을 사용하고 있기 때문에이 동작을 얻습니다. 문제는 이러한 변수가 모든 인스턴스간에 공유된다는 것입니다.

  var sp=0;
  var st=0;
  var t=0;
  var m='';
  var sa='';
  var l=0;
  var w=0;
  var gw=0;
  var ot=0;

스크립트의 반환 부분 또는 생성자에서 이러한 변수를 공개 인스턴스로 이동해야합니다 (이 경우 모든 변수에 대한 게터를 제공해야합니다).

return{

   // Place your variables here
   sp : 0,
   st : 0,

   ...

   build:function(sm,sw,mt,s,sl,h){
      // And then use the this keyword to access the variable
      this.sp=s;
      this.st=sw;
      t=mt;
      m=document.getElementById(sm);
      sa=m.getElementsByTagName('li');
      l=sa.length;     
      w=m.offsetWidth;     
      gw=w/l;
      ...
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top