无法调用函数为javascript中构造函数模式中的变量赋值

无法调用函数为javascript中构造函数模式中的变量赋值,javascript,Javascript,我试图通过调用calculateChartWidth()方法为变量(chartWidth)赋值 但我面临的错误是calculateChartWidth不是一个定义的函数 var ForceSimulationChart = function(){ this.width = document.querySelector("svg").clientWidth; this.height = document.querySelector("svg").clientHeight;

我试图通过调用calculateChartWidth()方法为变量(chartWidth)赋值

但我面临的错误是calculateChartWidth不是一个定义的函数

var ForceSimulationChart = function(){
    this.width = document.querySelector("svg").clientWidth;
    this.height = document.querySelector("svg").clientHeight;

    this.margin = {top:5, left:5, bottom:5, right:5 };

    //this.chartWidth = this.width - (this.margin.left+this.margin.right);
    //this.chartHeight = this.height - (this.margin.top+this.margin.bottom);

    this.chartWidth = this.calculateChartWidth();
    this.chartHeight = this.calculateChartHeight();

    this.svg = d3.select("#graph").append("svg");   
    this.chartLayer = this.svg.append("g").classed("chartLayer", true);

    this.calculateChartWidth = function(){
        return this.width - (this.margin.left+this.margin.right);
    }

    this.calculateChartHeight = function(){
        return this.Height - (this.margin.top+this.margin,bottom);
    }
}

从我看到的情况来看,调用函数时没有定义函数。在调用this.chartWidth=calculateChartWidth()之前,需要声明和定义函数

基本上,您拥有的是:

var dog = callUndefinedFunction();

var callUndefinedFunction = function() { 
    // ...
当您需要的是:

var callUndefinedFunction = function() { 
    // ...
};

var dog = callDefinedFunction();
查看代码优先的代码段(相当于您拥有的代码段),在调用
callUndefinedFunction
时,您正在访问一个未定义的变量:您尚未声明它或为它指定定义

通过将变量声明及其定义移到调用(第二个代码块)上方,可以避免此问题

但是你的代码仍然失败 我回去修改了你最初的问题——删除无关代码;但是,当您在调用
calculateCarthweight
时,您在其他地方的示例中的其他代码也会遇到同样的问题

calculateChartWidth
失败,因为它是插入代码的第一行

一旦这一问题得到解决,其余的将失败

但是你喜欢你点的菜吗
如果你不想移动一堆“东西”,你可以在Javascript的上下文中阅读。函数在Javascript中的“提升”方式与变量不同,因此请注意这一区别。

构造函数用于创建对象的实例。它们通常采用指定为属性的参数。参见MDN的


文档中是否有svg?调用-document.querySelector(“svg”)时会发生什么?如何调用
calculateChartWidth
?如果将函数定义分配给变量,则该变量不会被提升,这意味着从其定义上方调用该变量的对象不可用。请看这里:
// Object Constructor Functions
function Credential(id, username, password) {
    this.id = id;
    this.username = username;
    this.password = password;
}

//push object to credentials array
try {
    credentials.push(new Credential(id, username, password));
}
catch (e) {
    console.log('Error: Failed Adding Credential ' + id + '.');
    return;
}