JS에서 프로토 타이핑에 대해 약간 혼란 스럽습니다. 나는 이것에 대한 바이올린을 준비했습니다 :JS : 프로토 타이핑 - 올바른 인스턴스 속성에 액세스하십시오.
마크 업 :
<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 프로토 타입 기능에서 처리됩니다.
그러나 위의 코드로 잘못된 상자에 색이 표시됩니다. 올바른 컨테이너를 어떻게 처리합니까?
무엇이 여기에 있습니까?
자세한 답변 해 주셔서 감사합니다. 매력처럼 일했습니다. – algi