2011-07-01 5 views
1

저는 자바 스크립트 객체에 초보자이며 문제가 있습니다. 이미지 갤러리를 만들려고하지만 this.current, this.size & this.initial이 정의되어 있지 않으므로 스크립트가 작동하지 않는다는 오류가 계속 발생합니다. 이 오류를 해결하도록 도와주세요. 다음은 전체 스크립트입니다.자바 스크립트 객체를 사용하여 정의되지 않은 오류가 발생했습니다.

function gallery() 
{ 
    this.image = new Array(10); 
    this.initial = 1; 
    this.current = 0; 
    this.size = 10; 
    this.frame_height = 400; 
    this.frame_width = 600; 
    this.initialize=function() 
    { 
     if(document.images) 
     { 
      var count = 1; 
      for(count=1;count<=this.size;count++) 
      { 
       this.image[count] = new Image(); 
       this.image[count].src = 'images/'+count+'.jpg';     
      } 
     } 

    divImg.id = "divImg"; 
    divImg.setAttribute("Width",this.frame_width); 
    divImg.setAttribute("align","center"); 
    divImg.setAttribute("margin","0px auto"); 


    divBtn.id = "divBtn";  
    divBtn.setAttribute("align","center"); 
    divBtn.setAttribute("backgroung-color","Black"); 
    divBtn.setAttribute("color","White"); 
    divBtn.style.margin = "0px auto"; 
    divBtn.className ="btn"; 

    pictureFrame.src = this.image[this.initial].src; 
    pictureFrame.setAttribute('Width',this.frame_width); 
    pictureFrame.setAttribute('Height',this.frame_height); 
    pictureFrame.name = 'img'; 

    btnNext.innerHTML='NEXT'; 
    btnPrevious.innerHTML='PREVIOUS'; 
    btnLast.innerHTML='LAST'; 
    btnFirst.innerHTML='FIRST'; 

    btnFirst.onclick=this.first; 
    btnLast.onclick=this.last; 
    btnPrevious.onclick=this.previous; 
    btnNext.onclick=this.next; 

    myForm.appendChild(pictureFrame); 
    divImg.appendChild(myForm); 

    divBtn.appendChild(btnFirst); 
    divBtn.appendChild(btnPrevious); 
    divBtn.appendChild(btnNext); 
    divBtn.appendChild(btnLast); 

    pageBody.appendChild(divImg); 
    pageBody.appendChild(divBtn); 
    headerTag.appendChild(pageBody); 
} 

this.next=function() 
{ 
    alert(this.size); 
    alert(this.current); 
    if (this.current < this.size) 
    { 
     this.current +=1; 
     pictureFrame.src = this.image[this.current].src; 
    } 
    else 
    { 
     alert("This is the last image"); 
    } 
} 
this.previous=function() 
{ 
    alert(this.current); 
    alert(this.initial); 
    if (this.current > this.initial) 
    { 
     this.current = this.current-1; 
     pictureFrame.src = this.image[this.current].src; 
    } 
    else 
    { 
     alert("This is the first image"); 
    } 

} 
this.first=function() 
{ 
    this.current=this.initial; 
    pictureFrame.src = this.image[this.current].src; 
} 
this.last=function() 
{ 
    alert(this.size); 
    this.current=this.size; 
    pictureFrame.src = this.image[this.current].src; 
} 

}; 

var divImg= document.createElement('div'); 
var divBtn = document.createElement('div'); 
var btnFirst= document.createElement('button'); 
var btnNext= document.createElement('button'); 
var btnPrevious= document.createElement('button'); 
var btnLast= document.createElement('button'); 
var divTop = document.createElement('div'); 
var headerTag = document.getElementsByTagName('html')[0]; 
var pageBody = document.createElement('body'); 
var myForm=document.createElement("form"); 
var pictureFrame = document.createElement('img'); 


var pics=new gallery(); 
window.onload=pics.initialize(); 

답변

1

당신은 ECMA 스크립트를 처음 사용하는 사람들에게 매우 일반적인 범위 실패를 벗어난 을 expierencing하고 있습니다.

모든 함수는 자신의 실행 컨텍스트 그리고 ECMA-/ 자바 스크립트의 각 상황에 맞는 자체 this 컨텍스트 변수를 가지고있다. 이를 방지하려면, 가장 일반적인 방법은 지역 변수에서 "외부"this 상황 변수에 대한 참조를 저장하는 것입니다 :

function gallery() 
{ 
    this.image = new Array(10); 
    this.initial = 1; 
    this.current = 0; 
    this.size = 10; 
    this.frame_height = 400; 
    this.frame_width = 600; 

    var self = this; 

    //... 

    this.initialize=function() 
    { 
     if(document.images) 
     { 
      var count = 1; 
      for(count=1;count<=self.size;count++) 
      { 
       self.image[count] = new Image(); 
       self.image[count].src = 'images/'+count+'.jpg';     
      } 
     } 
    // ... 

이 모든 자바 스크립트 같은 환경에서 작동합니다. 그 동안 ECMA에서이 문제를 피하는 "더 좋은"방법이 있습니다. 예를 들어 ECMAscript Edition 5에는 메서드가 도입되어 this context variable의 참조를 원하는 개체에 "바인딩"할 수 있습니다. 많은 자바 스크립트 프레임 워크는 객체에 this을 바인딩하는 꽤 유사한 방법을 제공합니다. 자바 스크립트 자체조차도 약간의 노력으로이 작업을 수행 할 수 있습니다. window 객체가 pics.initialise를 호출 할 때 jAndy 말했다 무엇

1

(함수가 익명이 아닌 this는, 함수의 호출을 의미) thiswindow을 의미, 올바른 것입니다. this 것,

var pics = new gallery(); 
window.onload = function() { 
    pics.initialize(); 
}; 

를이 익명 함수에 싸여 있기 때문에 :

대신

var pics = new gallery(); 
window.onload = pics.initialize; 

의 당신은 할 수 있습니다 :

그러나 당신이 선호 할 수있는 간단한 해결책이있다 window 대신 gallery 인스턴스를 참조하십시오.

jAndy의 제안은 확실히 강력하지만 Javascript로 계속 괴롭히는 사람에게는 약간 어려울 수 있습니다.

관련 문제