2012-03-11 4 views
1

JS에서 프로토 타이핑에 대해 약간 혼란 스럽습니다. 나는 이것에 대한 바이올린을 준비했습니다 :JS : 프로토 타이핑 - 올바른 인스턴스 속성에 액세스하십시오.

http://jsfiddle.net/GBCav/7/

마크 업 :

<div class="container1"> 
    <p>Container 1</p> 
    <button>Turn me (container1) red</button> 
</div> 

<div class="container2"> 
    <p>Container 2</p> 
    <button>Turn me (container2) red</button> 
</div> 

JS :

// Create two instances of box 
(function() { 
    var container1 = new Box($('div.container1')); 
    container1.init(); 

    var container2 = new Box($('div.container2')); 
    container2.init(); 
})(); 
:

여기
// Constructor Function 
function Box(container) { 
    this.container = $(container); 
} 

// Prototype method 
Box.prototype = { 
    init : function() { 

     // Assign buttons to object variable 
     this.button = this.container.find('button'); 

     $this = this; // Set 'this' to Slider object 
     this.button.on('click', function() { 
     // It is getting the wrong container here, but why 
     $this.container.css('background-color','red'); 
     }); 
    } 
}; 

내가 생성자 함수를 호출하는 방법을

나는 두 개가있다. 생성자 함수에 의해 생성 된 상자 객체입니다. 상자 안의 버튼을 클릭하면 CONTAINING 상자의 배경색이 변경됩니다.

색상 변경은 상자의 init 프로토 타입 기능에서 처리됩니다.

그러나 위의 코드로 잘못된 상자에 색이 표시됩니다. 올바른 컨테이너를 어떻게 처리합니까?

무엇이 여기에 있습니까?

답변

1

당신은 var 문을 놓치고 :

var $this = this; 

var에 추가하고 예상대로 작동합니다 :

$this = this; 

는해야 http://jsfiddle.net/GBCav/8/

설명 : var를 생략하는 경우 키워드를 사용하면 $this을 범위로 제한된 것이 아닌 전역 변수에 할당합니다 방법은 .init()입니다. 이 할당은 .init()으로 호출 할 때 발생하므로 두 번째 인스턴스에서이 메서드를 호출하면 $this이 두 번째 인스턴스에 다시 할당되고 첫 번째 인스턴스의 이벤트 처리기에서 $this 값에 영향을줍니다.

+0

자세한 답변 해 주셔서 감사합니다. 매력처럼 일했습니다. – algi

관련 문제