我有一個簡單的類,盒: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