Javascript将窗口上下文传递给函数内部的框架调用

问题描述

我正在与neovis开发Neo4j图形界面,并尝试将我的代码外包。

我计划在Graph()函数获取图形需要的所有函数。 我想为我正在创建的每个图使用new Graph()创建一个新对象。

初始化图形时,我现在遇到Neovis框架的错误Uncaught (in promise) TypeError: this.body.container is null

我的猜测是,正确的上下文传递不正确。

初始化图形的代码

Graph.prototype.drawGraph = function(viz){
        this.viz = viz;
        this.viz = new NeoVis.default(this.config);
        this.viz.render();
    };

我还尝试通过将上下文传递给讲师并使用call()和apply()方法进行猜测来使其工作。

有没有一种方法可以传递正确的上下文并使其正常工作,而无需更改框架中的原始代码

编辑: 完整的工作流程:

//inside of normal window context
graphs[0] = new Graph(code,this);
            graphs[0].setConfig(config);
            graphs[0].setLimit(limit);
            graphs[0].createGraphArea(result,viz);


//inside of Graph function
this.createGraphArea = function(graph_data,viz){
        //create HTML
        
        if(Number.isInteger(graph_data[0]))
            this.createGraphTable(graph_data)
        else
            this.drawGraph(viz);
    }

解决方法

您可以在此处进行一些更改-

方法1)捕获窗口的this,因此在图形函数中-

// Outside the graph function,in global scope (window)
var self = this;

this.createGraphArea = function(graph_data,viz){
    //create HTML
    
    if(Number.isInteger(graph_data[0]))
        self.createGraphTable(graph_data);
    else
        self.drawGraph(viz);
}

方法2)使用提供词法作用域的ES6箭头功能-

this.createGraphArea = (graph_data,viz) => {
    //create HTML
    
    if(Number.isInteger(graph_data[0]))
        this.createGraphTable(graph_data);
    else
        this.drawGraph(viz);
};