jbburf
jbburf

Reputation: 131

How do you set top level property methods in a constructor based on a function call?

I have a constructor in a class that sets properties based on the arguments passed when creating the function as well as a call to another function based on those arguments but I am running into an issue. I have solved in with a work around but there must be a more elegant way to write this (no pun intended).

Here is my constructor:

constructor(name,model,version){
// create optional parameters to set basic values
this.name = name;
this.model = model;
this.version = version;

if(model === undefined || version === undefined){
  this.make = "";
  this.model = "";
  this.version = "";
  this.prop3 = 0
  this.prop4 = 0;
  this.prop5 = 0;
}
else{
  this = getVersionAttrs(model,version); }

This code does not work, if I replace this with this.what then the code functions but sets all of the properties as properties of OBJECT.what and not directly of the OBJECT.

I've replaced the else statement with the following that works:

else{
  temp = getVersionAttrs(model,version);
  for(var x in temp){ this[x] = temp[x]; }
}

Does anyone know how to assign this object I am getting back from the function getVersionAttrs() to the object that is being created? Aka properties of the returned object should become properties of the object being created.

Thanks in advance, I've been scratching my head over this one.

Upvotes: 2

Views: 76

Answers (3)

Stephen Kingsley
Stephen Kingsley

Reputation: 559

Hahaha, that is typical wrong. Let us review your code

this = getVersionAttrs(model,version);

I guess you want to Object.assign this value but you re assignment this value.

So, there is a simple solution below, about Object.assign

this = Object.assign({}, this, getVersionAttrs(model,version))

Also you can use lodash or other same APIs.

Upvotes: 0

MrPizzaFace
MrPizzaFace

Reputation: 8086

I'm not exactly sure what you're trying accomplish here, but from what I can see, I believe you should be set with something as simple as this:

constructor(name, model=null, version=null){      
  if (!model || !version) {
     var {model, version} = getVersionAttrs(model, version);
  }

  this.name = name;
  this.model = model;
  this.version = version;
}

Assuming getVersionAttrs(model, version) returns something like {model: 'model', version: 'version' }

Upvotes: 0

CertainPerformance
CertainPerformance

Reputation: 371233

Don't try to re-assign a this. If getVersionAttrs returns an object with properties you want to add to this, you should use Object.assign instead:

else {
  Object.assign(this, getVersionAttrs(model, version));
}

class MyClass {
  constructor() {
    Object.assign(this, { foo: 'foo' });
  }
}
console.log(new MyClass());

Upvotes: 2

Related Questions