1
我对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:
// 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');
});
}
};
这是我如何调用类的构造函数:
// Create two instances of box
(function() {
var container1 = new Box($('div.container1'));
container1.init();
var container2 = new Box($('div.container2'));
container2.init();
})();
我有两个由构造函数创建的Box对象。当我点击一个框内的按钮时,CONTAINING框的背景应该改变颜色。
颜色的变化是在Box的init原型函数中处理的。
但是,错误的方框正在变得上面的代码着色。我如何处理合适的容器?
我在这里错过了什么?
谢谢你的详细解答!像魅力一样工作。 – algi 2012-03-11 22:22:47