Class constructor, is it possible to set a property to be an object?

You use classes to make new objects which share similar construction. What if you want some of those object properties to be objects as well? For example:

const obj={
     prop: 'string',
     obj: { prop: 5 }
}

Can you make a class which creates similar objects while passing it a string and number value?

Definitely. Your class properties can hold any type of JS values. Why don’t you try creating a simple class with a constructor to show us what you are trying to do and if it doesn’t work paste your code here and we can help you troubleshoot.

class Example{
    constructor(string, num){
        this.obj={
            id:`${num}-id`, text: string+' '+num
        }
        this.obj2={
            number: num, class: string
        }
    }
}

Ok i made up this as an example. When i use new to create an object and type it in the console i dont get the expected result. I am also trying to include the props in more flexible way and i aint sure how attainable is that.

I’m not sure I understand what result you are expecting? The class code you have here looks good to me. I ran it on my computer and it works as expected. Can you give more details about what exactly you are trying to do?

1 Like

Yeah, it gets the result that I would expect:

class Example{
    constructor(string, num){
        this.obj={
            id:`${num}-id`, text: string+' '+num
        }
        this.obj2={
            number: num, class: string
        }
    }
}

const myEx = new Example('apple', 123);

console.log(JSON.stringify(myEx, null, 2));
// {
//   "obj": {
//     "id": "123-id",
//     "text": "apple 123"
//   },
//   "obj2": {
//     "number": 123,
//     "class": "apple"
//   }
// }

To reiterate what bbsmooth is asking… What result are you getting and what did you expect instead?

1 Like

sorry guys, i think i didnt read my console correct. So i did write it correctly after all?

It is proper JS, no syntax errors or anything. Whether it is working correctly for what you want to do? Only you can know that :slight_smile: But if you want to explain in more detail what you are trying to do then we might be able to offer suggestions if needed.

its a template to produce objects with data for similar elements in my app, holding id’s, text content etc and a lot of the values and code is repetitive beside a value and a key-word, so i wanted to test myself and come up with a constructor about it. They will also share functions among them, so it will be another challenge to add a method. I will post again if i come to a dead end

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.