2017-02-27 51 views
0

我有一個簡單的工廠返回一個數組和函數調用在角度工廠的變量:來自同一個工廠

function stockCommons() { 
     return { 
      unitTypes: [ 
       { 
        code: 'UN', 
        unitTypeIndex: 0 
       }, 
       { 
        code: 'PK', 
        unitTypeIndex: 2 
       }, 
      ], 

      unitTypeChanged: function (changedToUnitType) { 
       return var activeUnitType = stockCommons.unitTypes.filter(function (obj) { 
        return obj.code == changedToUnitType; 
       })[0]; 
     } 
    } 

在我試圖在stockCommons.unitTypes,使對數組的參考作用,但它不起作用。我試過these solutions,但他們也不工作。

如何在函數中使用unitTypes數組?

回答

1

簡單的解決方案是將unitTypes定義爲私有變量並引用它。

function stockCommons() { 
    var unitTypes = [{ 
      code: 'UN', 
      unitTypeIndex: 0 
     }, { 
      code: 'PK', 
      unitTypeIndex: 2 
     }, 
    ]; 

    return { 
     unitTypes: unitTypes, 

     unitTypeChanged: function (changedToUnitType) { 
      var activeUnitType = unitTypes.filter(function (obj) { 
        return obj.code == changedToUnitType; 
       })[0]; 
      return activeUnitType; 
     } 
    } 
} 
+0

抱歉,現在我明白了。謝謝。 – neptune

1
function stockCommons() { 
     return { 
      unitTypes: function() { 
       this.stock = [ 
       { 
        code: 'UN', 
        unitTypeIndex: 0 
       }, 
       { 
        code: 'PK', 
        unitTypeIndex: 2 
       }, 
       ]; 
       return this.stock; 
      }, 

      unitTypeChanged: function (changedToUnitType) { 
       return var activeUnitType = stockCommons.unitTypes.filter(function (obj) { 
        return obj.code == changedToUnitType; 
       })[0]; 
     } 
    }