2017-09-26 71 views
1

我想創建一些計量器,但是我的計量器對象保持未定義狀態。Javascript函數全局變量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 

爲什麼?我不能將變量傳遞給函數嗎?

+0

請,分享什麼是'JustGage'以及 –

+4

原語是按值傳遞,而'doesntwork'是'undefined' - 一種原始的。所以如果你在函數中將它修改爲'name',它對'doesntwork'變量沒有影響。你爲什麼不直接從函數的'new JustGage'返回結果呢? –

+0

它是一個JavaScript插件來創建儀表。請參閱https://github.com/toorshia/justgage – tipsfedora

回答

5

不,你只傳遞值,而不是變量引用或指針。

對於這個簡單的例子,返回似乎更合適。

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); 

不過,我敢肯定,這可能是過於簡化。 JS中有「引用類型」,因此如果works保存了一個對象,則可以傳遞對象引用的值並使函數填充該對象的屬性。

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); 
+0

謝謝,作品應該是。 – tipsfedora

+0

不客氣。 – llama