-3

I wonder how it would be possible to add subclasses to an object like I try to use in the code below.

The code is quite self explanatory for what I am trying to do. How can I add .id, .name and .lastname to an object?

var obj = getObjfunction(); //Get object with all info in it and show in console
console.log(obj.id);
console.log(obj.name);
console.log(obj.lastname);

function getObjfunction() {

    var obj;

    //I like to set 3 subclass to this "obj" like below. How to achieve this?
    obj.id = 0;
    obj.name = "Tom";
    obj.lastname = "Smith";
}
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Andreas
  • 1,121
  • 4
  • 17
  • 34

1 Answers1

3

What you seem to be looking for is a constructor. You would call it with new and initialise it in the constructor by referencing this:

var obj = new getObjfunction();
console.log(obj.id);
console.log(obj.name);
console.log(obj.lastname);

function getObjfunction() {
    this.id = 0;
    this.name = "Tom";
    this.lastname = "Smith";
}
trincot
  • 317,000
  • 35
  • 244
  • 286