2017-02-27 43 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]; 
     } 
    }