-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
  • 704,970
  • 168
  • 1,303
  • 1,425
Andreas
  • 975
  • 3
  • 12
  • 25

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
  • 263,463
  • 30
  • 215
  • 251