我有一个简单的类,盒:Coffeescript - 为什么我的类的属性未定义onclick?
class Box
constructor: (@idx, grid) ->
console.log("constructing", @idx)
@elem = document.createElement("div")
@elem.id = "box" + idx
@elem.className = "box"
@elem.onclick = @toggle
grid.appendChild(@elem)
toggle:() ->
alert("click")
console.log("My idx is: ", @idx)
当构造运行它报告“构建0”,“1建设”等,所以我知道正在定义的类属性。如果我调用b.toggle()(其中b是一个box实例),那么它会正确报告idx。但是,一旦我点击页面上的元素,它说@idx是未定义的。
所以看起来好像某种方式框的属性丢失在事物的onclick方面。为什么是这样?
以下是编译的JavaScript:
Box = (function() {
function Box(idx, grid) {
this.idx = idx;
console.log("constructing", this.idx);
this.elem = document.createElement("div");
this.elem.id = "box" + idx;
this.elem.className = "box";
this.elem.onclick = this.toggle;
grid.appendChild(this.elem);
}
Box.prototype.toggle = function() {
alert("click");
return console.log("My idx is: ", this.idx);
};
return Box;
})();
谢谢!
谢谢你,工作。 – dandelion 2013-03-10 23:34:39