2013-01-22 2 views
0

이 바로 "이"ImageCarousel 클래스 내부 바르를 참조 사용하기위한저는 "this"를 JavaScript에서 올바르게 사용하고 있습니까?

ImageCarousel = (function() { 
var currentIndex, imageManager, imagesVO, jsonPath, values; 

currentIndex = null; 

jsonPath = "json/images.json"; 

imagesVO = []; 

values = null; 

imageManager = null; 

function ImageCarousel() { 
    this.loadJson(); 
} 

ImageCarousel.prototype.loadJson = function() { 
    var _this = this; 
    return $.ajax(jsonPath, { 
    success: function(data, status, xhr) { 
     console.log("yea " + data); 
     _this.currentIndex = 0; 
     _this.imagesVO = data.images; 
     _this.imageManager = new ImageManager(data.images); 
     _this.imagesCount = _this.imagesVO.length; 
     _this.switchToImage(_this.currentIndex); 
     $('#next').click(function() { 
     _this.currentIndex = _this.incrementIndexByOne(_this.currentIndex); 
     return _this.switchToImage(_this.currentIndex); 
     }); 
     return $('#prev').click(function() { 
     _this.currentIndex = _this.decrementIndexByOne(_this.currentIndex); 
     return _this.switchToImage(_this.currentIndex); 
     }); 
    }, 
    error: function(xhr, status, err) { 
     return $('#imageHolder').html("problem loading the json file, </br>make sure you are running this on your local server"); 
    }, 
    complete: function(xhr, status) {} 
    }); 
}; 

내가 나는 내 코드? 그 물건들을 공개하니? 그렇다면 어떻게 그들을 비공개로 유지할 수 있습니까?

+0

어떻게 'this'를 사용하고 싶습니까? 'this'와 그 중 많은 것들을 사용하는 몇 가지 방법이 있습니다. 개인 정보는 노출시키지 않고 만들 수 있습니다. 'this '에 추가하면 노출 된 것입니다. – Halcyon

+0

'_this' 대신에'var'을 사용하지 않으셨습니까? – Alexander

답변

0

아니요. this을 올바르게 사용하지 않으 셨습니다. 외부 코드가 ImageCarousel이라는 일부 속성을 호출하여 실제로 액세스 할 수 있으므로 참조하려는 속성은 모두 비공개입니다.

어떤 이유로 든 변수를 공개하려는 경우 var을 사용하여 선언하지 마십시오. 대신 this.currentIndex = null 또는 this.jsonPath = "json/images.json"과 같은 작업을 수행하십시오. 그렇게하면 본질적으로 해당 속성을 공개적으로 액세스 할 수있게됩니다. 모든 외부 코드는 ImageCarousel.currentIndex, ImageCarousel.jsonPath 등을 호출하여 해당 속성에 액세스 할 수 있습니다.

+0

나는 이해하지 못한다.ImageColusel() 함수를 사용하는 경우 { imageHolderDiv = $ ('# imageHolder'); loadJson(); // 잡히지 않음 ReferenceError : loadJson이 정의되지 않았습니다. } – nuway

0

몇 가지 문제가 있습니다.

var ImageCarousel = function() { 
    var currentIndex, imageManager, imagesVO, jsonPath, values; 

    currentIndex = null; 

    jsonPath = "json/images.json"; 

    imagesVO = []; 

    values = null; 

    imageManager = null; 

    var _this = this; 

    this.loadJson = function() { 
     return $.ajax(jsonPath, { 
      success: function (data, status, xhr) { 
       console.log("yea " + data); 
       currentIndex = 0; 
       imagesVO = data.images; 
       imageManager = new ImageManager(data.images); 
       imagesCount = imagesVO.length; 
       switchToImage(currentIndex); 
       $('#next').click(function() { 
        currentIndex = _this.incrementIndexByOne(currentIndex); 
        return _this.switchToImage(_this.currentIndex); 
       }); 
       return $('#prev').click(function() { 
        currentIndex = _this.decrementIndexByOne(currentIndex); 
        return _this.switchToImage(currentIndex); 
       }); 
      }, 
      error: function (xhr, status, err) { 
       return $('#imageHolder').html("problem loading the json file, </br>make sure you are running this on your local server"); 
      }, 
      complete: function (xhr, status) {} 
     }); 
    }; 
    this.loadJson();  
}; 

var someCarousel = new ImageCarousel(); // Example usage. 

효과적으로 ImageCarousel 두 번 선언 : 여기에 수정/w 코드입니다. 한 번 ImageCarousel = (function() { 및 한 번 function ImageCarousel().... 나는 전자를 선택했다.

정확하게 이해했다면 currentIndex, imageManager, imagesVO, jsonPath 및 값을 비공개로 설정해야합니다. 그것들을 위해서 함수 블록 안에 var를 넣으면 그것들은 그 new 오브젝트의 각 인스턴스에 대해 private이 될 것입니다. ImageCarousel 함수 내에서 안전하게 사용할 수 있으며 걱정하지 않아도됩니다 (그리고 _this은 없습니다).

_thisloadJson이라고 부르는 메서드에 남겨 둡니다. 여기에 정의 된 내용을 볼 수 없기 때문에 public 메서드라고 가정합니다. 그들이 사적인 것이라면, 래퍼 함수 안에 선언하면 내부에서만 액세스 할 수 있습니다. 공개로 설정하려면 loadJson과 마찬가지로 this[functionName]을 사용하십시오.

그래서 내 코드 변경의 영향은 다음과 같습니다 등

  • currentIndex는 개인이다.
  • loadJson은 공개입니다.

편집prototype을 사용하는 방법에 대한 자세한 것. prototype은 "정적"기능을위한 것입니다. 즉, 해당 기능이 ImageCarousel 개체의 모든 인스턴스에 존재하지 않는다는 의미입니다. 그것을 사용한다면 함수의 선언문 밖에서 사용해야합니다. 그렇지 않으면 newImageCarousel 때마다 불필요하게 loadJson을 재정의 할 것입니다. 다음은 좀 더 명확하게 의미하는 것을 보여주는 멋진 데모 응용 프로그램입니다. http://jsfiddle.net/d2BbA/

관련 문제