我創建了一個包含方法redraw()
的對象Chart
。因爲從redraw()
內的this
的上下文已從Chart
對象更改爲DOM元素,所以我無法訪問對象Chart
的屬性(例如:this.data
)。在Javascript中引用對象的方法
的jsfiddle:http://jsfiddle.net/a4tbG/1/
試着在灰色框拖拽到觸發redraw()
問題:如何從功能chart.redraw
訪問父對象chart.data
?
chart = new Chart();
chart.init();
function Chart() {
this.data = [1, 2, 3];
this.init = function() {
var zoom = d3.behavior.zoom()
.on("zoom", this.redraw);
d3.select('#chart')
.append('svg:svg')
.attr('width', 300)
.attr('height', 300)
.call(zoom);
}
this.redraw = function() {
console.log(this); // Output the DOM element #chart svg. How do you access the object?
console.log(this.data);
}
}
使用'bind()的'在dystroy的答案,或者使用'$ .proxy(this.redraw,這一點)'支持舊的瀏覽器 –
@ A.Wolff瀏覽器不綁定不支持畫布或SVG。 –
@dystroy該死的;;) –