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

时间:2017-09-19 16:30:11

标签: javascript

我试图通过调用方法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);
    }
}

2 个答案:

答案 0 :(得分:1)

从我所看到的,您调用它时未定义您的功能。您需要在致电this.chartWidth = calculateChartWidth();

之前声明并定义您的功能

基本上,你拥有的是:

var dog = callUndefinedFunction();

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

当你需要的是:

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

var dog = callDefinedFunction();

查看代码的第一个代码片段(相当于你所拥有的代码片段),你在调用callUndefinedFunction时 - 访问一个未定义的变量:你没有声明它或为它分配了一个定义。

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

但您的代码仍然失败

我已经回去修改你的初始问题 - 删除多余的代码;但是,您在其他地方的示例中遇到与其他代码相同的问题,因为您在调用calculateChartHeight时重复了同样的问题。

calculateChartWidth失败,因为它是您的代码中断的第一行。

一旦解决了,其余的都会失败。

但你喜欢你的订购

好吧,如果你不想移动一堆“东西”,你可以在Javascript的上下文中阅读hoisting。 Javascript中的函数与变量的“悬挂”不同,因此要注意这种区别。

答案 1 :(得分:0)

构造函数用于创建对象的实例。它们通常采用被指定为属性的参数。请参阅MDN' Working with objects

// 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;
}