Furman Furman - 1 year ago 78
Javascript Question

Javascript class constructor with parameter used as key from object literal

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

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

class Test {
this.property1 = propertyList.typ.property1;

var a = new Test('type1');

Code is pretty self-explanatory - I want to set
property of
object not by passing value manually in constructor, but rather chosing one of values from
object literal by passing one of its key to constructor. I expected that when I run above code, object
will be created with
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
. Why above code doesn't work and can it be fixed somehow?

Answer Source

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;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download