-1

Title might be a little confusing, but I have following problem:

var propertyList = {
    type1: {property1: 1},
    type2: {property1: 2}
}

class Test {
    constructor(typ){
        this.property1 = propertyList.typ.property1;
    }
}

var a = new Test('type1');

Code is pretty self-explanatory - I want to set property1 property of a object not by passing value manually in constructor, but rather chosing one of values from propertyList object literal by passing one of its key to constructor. I expected that when I run above code, object a will be created with property1 value set to 1. However instead of that I got Uncaught TypeError: Cannot read property 'property1' of undefined error. When I pust console.log(typ) in the first line of constructor, it correctly shows that value passed into constructor is type1. Why above code doesn't work and can it be fixed somehow?

Furman
  • 2,017
  • 3
  • 25
  • 43
  • 1
    You need to use this syntax : `propertyList[typ].property1` otherwise it will look for the property name **typ** in the propertyList object (and this property doesn't exist) – Olivier Boissé Aug 05 '16 at 12:28

1 Answers1

0

Your syntax is a little off. You can't use the passed-in argument typ in your assignment like that because the code will then actually look for the property typ within propertyList (like propertyList { typ: }). To use your passed-in argument, wrap it in brackets:

this.property1 = propertyList[typ].property1;
skyline3000
  • 7,639
  • 2
  • 24
  • 33