【发布时间】:2019-01-13 21:34:44
【问题描述】:
我对 Javascript 非常陌生,我只是坚持使用在 python 中工作的东西。 问题是我有一个类,我在其中启动一些空列表,如 this.data_y_json 等。如果我在类中创建普通函数,如 normal_function(){this.data_y_json = 5} 它可以工作并且变量被更改。 但是,我使用 d3,并且有一些我无法通过的技巧:
// inside class
// in constructor all this.xxx defined
// after object initiation I call set_data()
set_data(){
d3.json("link2.json",function(data) {
for (var i=0;i<data.d.results.length;i++){
this.data_y_json.push(parseFloat(data.d.results[i].PE))
...
//end of function
// end of class
调用函数 set_data() 后出现错误:SCRIPT5007: Unable to get property 'data_y_json' of undefined or null reference
我正在将我的可视化重写为 OOP,在此之前,我用全局变量解决了它,它工作得很好。在 python 中,我只是将 'self' 作为参数传递给函数,但在 javascript 中,传递 THIS 不起作用并引发另一个错误。
简单地说,我知道问题 -> this.data_y_json 无法正确识别,因为函数(数据)没有传递对象的自我,但我不知道该怎么做。
提前感谢您的建议
【问题讨论】:
-
又快又脏:在方法开头定义
var self = this;,然后用self代替this
标签: javascript class variables d3.js this