【问题标题】:Javascript - pass THIS in function doesnt workJavascript - 在函数中传递这个不起作用
【发布时间】: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 无法正确识别,因为函数(数据)没有传递对象的自我,但我不知道该怎么做。

提前感谢您的建议

【问题讨论】:

  • this post
  • 又快又脏:在方法开头定义var self = this;,然后用self代替this

标签: javascript class variables d3.js this


【解决方案1】:

您在 ES2015 环境中吗?将您的回调更改为箭头函数应该将this 的范围设为您想要的

d3.json("link2.json", (data) => {
    for (var i=0;i<data.d.results.length;i++){
        this.data_y_json.push(parseFloat(data.d.results[i].PE))

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions

用于阅读箭头函数和 this 的范围

【讨论】:

  • 箭头函数等价于function () 语法,它只是语法糖,更容易为小型 lambda 编写
  • @rioV8 箭头函数等同于常规函数,也不是更易于编写的版本:箭头函数没有自己的this ,它们没有arguments 对象,它们不能用new 调用,它们有隐含的return 等。区别很多。
  • @GerardoFurtado:这可能就是为什么有时d3.select(this) 不起作用而我不得不使用d3.select(nodes[i]) 的原因。如果您使用{},则不会隐式返回
  • @rioV8 是,但不是有时d3.select(this) 永远不会在箭头函数中工作,正如我所解释的 hereherehere 和 @ 987654325@.
猜你喜欢
  • 2016-01-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-04-03
  • 2018-06-29
  • 1970-01-01
  • 2021-10-28
  • 1970-01-01
相关资源
最近更新 更多