0

I'm building an angular application and I have a class that I'm defining within another ts file. I'm trying to get a property that is defined by the constructor but I'm within an object that is in another object. Normally I would use the "this" keyword but it is referring to the object I am in and not the parent class.

here is the use of the class:

var devList = new DateList(dates)

here is a simplified version of the DateList class:

export class DateList {
  date
  constructor(input){
    this.date = input
  }

  devs = {
    bluegreen: {
      dates: this.date.bluegreen //<-----------I believe "this" in this 
                                 //            case refers to bluegreen, 
                                 //            how do I get it to refer
                                 //            to this instance of the 
                                 //            DateList class?
    }
  }

}

EDIT
I'm a beginner to programing so I don't understand what a function has to do with an object, inside of another object. can anyone explain how to fix the issue, and how the issue applies to functions?

Raphael Castro
  • 907
  • 1
  • 8
  • 26
  • Does this answer your question? [Typescript "this" inside a class method](https://stackoverflow.com/questions/16157839/typescript-this-inside-a-class-method) – lionthefox Dec 06 '19 at 20:10

1 Answers1

1

Setting class attributes happens before the constructor, so this.date is undefined when you are declaring the class attribute 'devs'. Move setting 'devs' inside the constructor and it will work:

export class DateList {

  private date: any;
  public devs: Object;

  constructor(input: Object){
    this.date = input

    this.devs = {
      bluegreen: {
        dates: this.date.bluegreen
      }
    }
  }
}

let dateList: DateList = new DateList({
  bluegreen: 'bluegreen_val'
});

console.log(dateList.devs);
Ezra
  • 802
  • 4
  • 11