David
David

Reputation: 1174

Javascript Function Global Variable undefined?

I want to create some gauges, but my Gauge object remains undefined.

var doesntwork;
function create_gauge(name, id,  min,  max,  title,  label) {
  name = new JustGage({
    id: id,
    value: 0,
    min: min,
    max: max,
    donut: false,
    gaugeWidthScale: 0.3,
    counter: true,
    hideInnerShadow: true,
    title: title,
    label: label,
    decimals: 2
  });
}
create_gauge(doesntwork, "g2", 0, 100, "Füllstand", "%");
console.log(doesntwork); //undefined

why? can't i pass variables to a function?

Upvotes: 1

Views: 150

Answers (1)

llama
llama

Reputation: 2537

No, you only pass values, not variable references or pointers.

For that simple example, returning would seem more appropriate.

var works;
function create_gauge(id,  min,  max,  title,  label) {
  return new JustGage({
    id: id,
    value: 0,
    min: min,
    max: max,
    donut: false,
    gaugeWidthScale: 0.3,
    counter: true,
    hideInnerShadow: true,
    title: title,
    label: label,
    decimals: 2
  });
}
works = create_gauge("g2", 0, 100, "Füllstand", "%");
console.log(works);

However, I'm sure this is probably overly simplified. There are "reference types" in JS, so if works held an object, you could pass the value of the object reference and have the function populate a property of the object.

var works = {};
function create_gauge(obj, id,  min,  max,  title,  label) {
  obj.data = new JustGage({
    id: id,
    value: 0,
    min: min,
    max: max,
    donut: false,
    gaugeWidthScale: 0.3,
    counter: true,
    hideInnerShadow: true,
    title: title,
    label: label,
    decimals: 2
  });
}
create_gauge(works, "g2", 0, 100, "Füllstand", "%");
console.log(works.data);

Upvotes: 5

Related Questions