如何在多个函数中设置参数,然后切换并保留

How can I set a parameter in multiple functions and then have it switched and persist

我知道这是一个糟糕的标题,但这是我能想到的最好的标题,让我看看是否可以解释它:

我有一个图表,由于图表和数据的性质,我使用了两个函数并隐藏了 div。除了这两个函数,我还有两种不同类型的图表(烛台和折线图)。我需要能够让某人设置图表的 'type'(蜡烛图或折线图),然后能够在 'type' 保持不变的情况下更改图表的时间段。

到目前为止,我倾向于使用全局 'type' 变量,但我知道使用全局变量并不是一个很好的做法,而且即使除了它不工作)。代码基本上是这样的:

type = 'line';

function makeDayChart(type, days){
    if(type == 'line'){
    *make line chart*
  } else {
    *make candle chart*
  }
}

function makeHourChart(type, hours){
    if(type == 'line'){
    *make line chart*
  } else {
    *make candle chart*
  }
}

这种方法对我来说有点道理,但我知道这不是实现它的方法。我一直在尝试为此研究一种方法,但今天还没有找到任何东西,如果您知道任何关键字或任何适用的东西,我将不胜感激。

这是一个 jsbin,它显示了我为此编写的代码,它显然不起作用,但是......它是一些东西。

感谢您花时间阅读本文。

http://jsbin.com/nusufohosi/1/edit?html,js,console,output


考虑到@magreenberg的回答,我尝试实现了。这是一个更新:

JSBin

听起来你要找的是一个构造函数。 JS 构造函数是 JS 最接近 类 的东西。例如,您有一个构建图形并保存其所有属性的构造函数

// SETUP Chart constructor function
function Chart(type, time){
    this.type = type;
    this.time = time
}

Chart.prototype.buildChart = function(){
     if (this.time === "hour"){
        if (this.type === "line"){
            // build hour line chart
        } else if(this.type ==="candle"){
            // build hour candle chart
        }
     } else if (this.time === "days"){
        if (this.type === "line"){
            // build days line chart
        } else if(this.type ==="candle"){
            // build days candle chart
        }
     }
}

// Instantiate new object
var chartA = new Chart("line", "days");
var chartB = new Chart("chandle", "hours");

// call graph function to build object
chartA.buildChart();
chartB.buildChart();

构造函数可能很难理解。特别是涉及到原型链接时。希望这能让您朝着正确的方向开始。